Sort by hash element

If I have an array of hashes, eg

[{‘name’=>‘Anna’, ‘score’=>11}, {‘name’=>‘Bryce’, ‘score’=>7},
{‘name’=>‘Chris’, ‘score’=>9}]

Is there an easy, Ruby-idiomatic way to sort this array by the 'score’
elements of each hash? eg so I get

[{‘name’=>‘Bryce’, ‘score’=>7}, {‘name’=>‘Chris’, ‘score’=>9},
{‘name’=>‘Anna’, ‘score’=>11}]

Thanks,
Tim Bates

···


tim@bates.id.au

Is there an easy, Ruby-idiomatic way to sort this array by the 'score'
elements of each hash? eg so I get

Well, you can give it a block

pigeon% ri Array#sort
------------------------------------------------------------- Array#sort
     arr.sort -> anArray
arr.sort {| a,b | block } -> anArray

···

------------------------------------------------------------------------
     Returns a new array created by sorting arr. Comparisons for the
     sort will be done using the <=> operator or using an optional code
     block. The block implements a comparison between a and b, returning
     -1, 0, or +1.
        a = [ "d", "a", "e", "c", "b" ]
        a.sort #=> ["a", "b", "c", "d", "e"]
        a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]

pigeon%

pigeon% ruby
a = [{'name'=>'Anna', 'score'=>11}, {'name'=>'Bryce', 'score'=>7},
{'name'=>'Chris', 'score'=>9}]
b = a.sort {|k,l| k['score'] <=> l['score']}
p b
^D
[{"score"=>7, "name"=>"Bryce"}, {"score"=>9, "name"=>"Chris"},
{"score"=>11, "name"=>"Anna"}]
pigeon%

Guy Decoux

In Ruby 1.7x you could use the nice Array#sort_by:

a = […]
a.sort_by { |x| x[“score”] }
==>[{“score”=>7, “name”=>“Bryce”}, {“score”=>9, “name”=>“Chris”},
{“score”=>11, “name”=>“Anna”}]

···

On Wed, 2002-11-27 at 11:54, Tim Bates wrote:

Is there an easy, Ruby-idiomatic way to sort this array by the ‘score’
elements of each hash? eg so I get