ruby

ruby sort_by method


I have just started to learn ruby. I have an array of hashes. I want to be able to sort the array based on an elementin the hash. I think I should be able to use the sort_by method. Can somebody please help?

#array of hashes
array = []
hash1 = {:name => "john", :age => 23}
hash2 = {:name => "tom", :age => 45}
hash3 = {:name => "adam", :age => 3}
array.push(hash1, hash2, hash3)
puts(array)

Here is my sort_by code:

# sort by name
array.sort_by do |item|
    item[:name]
end
puts(array)

Nothing happens to the array. There is no error either.


Solution

  • You have to store the result:

    res = array.sort_by do |item|
        item[:name]
    end 
    puts res
    

    Or modify the array itself:

    array.sort_by! do |item| #note the exclamation mark
        item[:name]
    end 
    puts array