3

I'm looking to return a new hash based on the reordering of values in the hash. The values, themselves, are arrays of ints.

For example:

hsh = {"c2" => [44,2], "c1" => [11,33], "c9" => [23,7]}

I would like to be able to return a reordered hash based on either value 0 or value 1 in the values.

Any help here is much appreciated - thanks all.

2
  • 1
    actually, rails has an ordered hash, and iirc, ruby 1.9 has an ordered hash too... Commented May 20, 2011 at 23:54
  • Ruby 1.9 remembers the insertion order of the hash, but it doesn't order it. Commented May 21, 2011 at 4:20

1 Answer 1

5

From the nature of the question, I assume this is for ruby 1.9.

p Hash[hsh.sort_by{|k, v| v[0]}]
# => {"c1"=>[11, 33], "c9"=>[23, 7], "c2"=>[44, 2]}

p Hash[hsh.sort_by{|k, v| v[1]}]
# => {"c2"=>[44, 2], "c9"=>[23, 7], "c1"=>[11, 33]}
Sign up to request clarification or add additional context in comments.

3 Comments

Just what I was looking for @sawa - thank you. And yes, this is ruby-1.9.2
How do you apply sort_by to hash when it's not listed as a method of that class?
@Jeremy In my case, I do it as usual because I already know how to use it. In your case, you can either (i) ask that as an independent question on Stackoverflow, (ii) look for better documentation, (iii) try to find a documentation more seriously using ri, rdoc, or (iv) just try it with various examples until you can infer how it works.

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.