138

This Ruby 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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Ollie Glass
  • 19,455
  • 21
  • 76
  • 107

4 Answers4

249

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 Ruby 1.8. In practice, you can do:

sorted = sort_me.sort_by { |k| k["value"] }
puts sorted

As of Ruby 1.9+, .sort_by! is available for in-place sorting:

sort_me.sort_by! { |k| k["value"]}
Nowaker
  • 12,154
  • 4
  • 56
  • 62
Stéphan Kochen
  • 19,513
  • 9
  • 61
  • 50
21

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

sort_me.sort! { |x, y| x["value"] <=> y["value"] }
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
bjg
  • 7,457
  • 1
  • 25
  • 21
8

Although Ruby doesn't have a sort_by in-place variant, you can do:

sort_me = sort_me.sort_by { |k| k["value"] }

Array.sort_by! was added in 1.9.2

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
AG_
  • 81
  • 1
  • 1
2

You can use sort_me.sort_by!{ |k| k["value"]}. This should work.

Mukesh Kumar Gupta
  • 1,567
  • 20
  • 15