0

My array is:

[{:age=>28, :name=>"John", :id=>1}, {:name=>"David", :age=>20, :id=>2}]

Order:

[:id, :name, :age] or ['id', 'name', 'age']

The result should be:

[{:id=>1, :name=>"John", :age=>28}, {:id=>2, :name=>"David", :age=>20}]

P/s: I am using Ruby 1.8.7 and Rails 2.3.5

Thanks

Joel
  • 4,503
  • 1
  • 27
  • 41
Anh
  • 27
  • 1
  • 6

2 Answers2

2

Order doesn't matter when it comes to hashes. You do not need to do that. Trust me.

What you're using is an Hash which, unlike Array doesn't care for positions. You only access the value by it's Symbol or Key.

So, there is no need of doing what you want to.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

As others have said, you cannot do that with Ruby 1.87 or prior. Here is one way to do that with Ruby 1.9+:

arr = [{:age=>28, :name=>"John", :id=>1}, {:name=>"David", :age=>20, :id=>2}]
order = [:id, :name, :age]

arr.map { |h| Hash[order.zip(h.values_at(*order))] }
  #=> [{:id=>1, :name=>"John", :age=>28}, {:id=>2, :name=>"David", :age=>20}] 

In Ruby 2.0+, you can write:

arr.map { |h| order.zip(h.values_at(*order)).to_h }

I thought 1.8.7 went out with the steam engine.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100