How do I sort an array of hashes by a value in the hash?

95,184

Solution 1

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"]}

Solution 2

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

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

Solution 3

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

Solution 4

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

Share:
95,184
Ollie Glass
Author by

Ollie Glass

Data scientist, machine learning engineer &amp; data strategist. ollieglass.com @ollieglass

Updated on July 17, 2020

Comments

  • Ollie Glass
    Ollie Glass almost 4 years

    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.

  • Marc-André Lafortune
    Marc-André Lafortune almost 14 years
    Actually, Array#sort_by! is new in Ruby 1.9.2. Available today to all Ruby version by requiring my backports gem too :-)
  • tekknolagi
    tekknolagi over 11 years
    Hi, is there a way to sort in descending order too? I figure I might want to go 3,2,1...
  • Stéphan Kochen
    Stéphan Kochen over 11 years
    You can't do that with sort_by, but use sort or sort! and simply flip the operands: a.sort! {|x,y| y <=> x } (ruby-doc.org/core-1.9.3/Array.html#method-i-sort)
  • Zaz
    Zaz almost 11 years
    Or: puts sorted = sort_me.sort_by{ |k,v| v }
  • Zaz
    Zaz almost 11 years
    @tekknolagi: Just append .reverse.
  • Islam Azab
    Islam Azab over 9 years
    @Shtééf It is doable via both methods.
  • AMIC MING
    AMIC MING over 8 years
    good source of information. Thanks, your answer really help me
  • web spider26
    web spider26 over 7 years
    This "Array.sort_by! was added in 1.9.2" answer worked for me
  • Salma Gomaa
    Salma Gomaa over 6 years
    For reverse you can check: stackoverflow.com/a/38362351/1770571