U-L
U-L

Reputation: 2681

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.

Upvotes: 25

Views: 42616

Answers (3)

You can use sort by method in one line :

array.sort_by!{|item| item[:name]} 

Upvotes: 0

ray
ray

Reputation: 5552

You can do it by normal sort method also

array.sort { |a,b| a[:name] <=> b[:name] }

Above is for ascending order, for descending one replace a with b. And to modify array itself, use sort!

Upvotes: 1

steenslag
steenslag

Reputation: 80065

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

Upvotes: 43

Related Questions