Search code examples
ruby-on-railsrubyarraysruby-on-rails-2ruby-1.8.7

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


Solution

  • 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.