简体   繁体   中英

Ruby on Rails - How to arrange elements of array in particular order

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM