views:

84

answers:

2

Hello,

this code is not behaving as I would expect:

# create an array of hashes
sort_me = []
sort_me.push({"value"=>1, "name"=>"a"})
sort_me.push({"value"=>3, "name"=>"c"})
sort_me.push({"value"=>2, "name"=>"b"})

# sort
sort_me.sort_by { |k| k["value"]}

# same order as above!
puts sort_me

I'm looking to sort the array of hashes by the key "value", but they are printed unsorted.

Any suggestions?

Thanks.

+5  A: 

Ruby's sort doesn't sort in-place. (Do you have a Python background, perhaps?)

Ruby has sort! for in-place sorting, but there's no in-place variant for sort_by. In practice, you can do:

sorted = sort_me.sort_by { |k| k["value"] }
puts sorted
Shtééf
Actually, `Array#sort_by!` is new in Ruby 1.9.2. Available today to all Ruby version by requiring my `backports` gem too :-)
Marc-André Lafortune
+3  A: 

As per @shteef but implemented with the sort! variant as suggested

sort_me.sort! { |x, y| x["value"] <=> y["value"] }
bjg