I'd think this would be easy, and have searched for this pretty hard, but can't seem to get it to work.
I have the following hash:
@friends = [{"name"=>"John Smith", "id"=>"12345"}, {"name"=>"Jane Doe", "id"=>"23456"}, {"name"=>"Samuel Jackson", "id"=>"34567"}, {"name"=>"Kate Upton", "id"=>"45678"}]
I'm trying to sort it alphabetically by the name.
Right now I"m doing this:
@friends.sort{|a,b| a[0]<=>b[0]}
However, it just outputs the full results in non-alphabetical order.
The problem is that a and b are Hash, so you have to use "name" as the key or index instead of 0. So this should do it
@friends.sort{|a,b| a['name']<=>b['name']}
Also remember to use sort! to modify @friends variable or set it to the result
@friends.sort!{|a,b| a['name']<=>b['name']}
or
@friends = @friends.sort{|a,b| a['name']<=>b['name']}
It is possible to sort by a key, just be aware if the key is a string or a symbol when doing this.
@friends.sort_by { |f| f['name'] }
If you want to make it case insensitive then you can always do:
@friends.sort_by { |f| f['name'].downcase }
And of course you can always use !
to save that back to @friends
>> @friends.sort_by! { |f| f['name'] }
>> @friends # now returns the sorted array of hashes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With