25

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.

3 Answers 3

43

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I just also figured out the same. Saw another sort_by example. So sort_by does not do inplace.
Bang methods (Those ending with !) modify in place, but it's good practice to not use them and create new objects as modified versions of old ones. Subtle bugs can be introduced into your programs by allowing methods to mutate your objects.
1

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!

Comments

1

You can use sort_by! method in one line:

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

This will mutate the original array object.

1 Comment

It repeats accepted answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.