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

2
  • 4
    Order is not maintained in Hash, of Ruby 1.8.7 Commented Feb 9, 2015 at 16:54
  • 2
    If you want ordered hashes you'll need to upgrade to Ruby 1.9+. Commented Feb 9, 2015 at 17:43

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

OP clearly requested to sort an array and you are talking about hashes.
OP is obviously talking about hashes too, if you read the question.
@ChrisHeald Yes, I misread a question as “sort an array by hash values.” My apologies.
I beg to differ. I have made good use of Ruby's maintenance of key insertion order in v. 1.9+.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.