Charlie Davies
Charlie Davies

Reputation: 1834

Sort a hash Ruby

I have a hash that looks like this

h1 = {"4c09a0da6071a593f051de32"=>["4c09a0da6071a593f051de32", "Cafe Bistro", 37.78458803130115, -122.40743637084961, 215.0], "4abbb03ef964a520668420e3"=>["4abbb03ef964a520668420e3", "The Plant Cafe Organic", 37.7977805076241, -122.3957633972168, 83.0] }

I would like to sort it by the final value in each hash e.g. 83.0, 215.0

I have tried

h1 = h1.sort_by{|k,v| v[4]}

but in out puts an array not a hash, i would like to keep the hash the same just reordered... how do I do this?

Upvotes: 2

Views: 1098

Answers (2)

Niklas B.
Niklas B.

Reputation: 95358

You need to convert the array back to a hash:

h1 = Hash[h1.sort_by { |_,v| v[-1] }]

Note that this only works since Ruby 1.9. Before that, hashes were not an ordered data structure.

Upvotes: 1

DigitalRoss
DigitalRoss

Reputation: 146251

It's not a great idea to count on ordering in a Hash. Ruby didn't order hashes at all in 1.8. The data structure in its canonical form is not ordered.

It's better style to use an Array when ordering is important and a Hash or something else when key lookup is needed.

There is a grey area when writing tests. In that case, it may be reasonable to depend on Hash ordering since you are testing a specific Ruby program in certain conditions and you have, after all, a test that can fail should the implementation assumptions ever change.

Upvotes: 2

Related Questions