Sort hashes in an array alphabetically by field

I would have thought it would be easy, and searched for it is quite difficult, but it seems it cannot make it 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 am trying to sort it alphabetically by name.

Now I am doing this:

@friends.sort{|a,b| a[0]<=>b[0]}

However, it simply displays the full results in alphabetical order.

+5
source share
2 answers

The problem is that a and b are Hash, so you need to use the "name" as the key or index instead of 0. So this should do it

@friends.sort{|a,b| a['name']<=>b['name']}

Also do not forget to use sorting! change @friends variable or set it to result

@friends.sort!{|a,b| a['name']<=>b['name']}

or

@friends = @friends.sort{|a,b| a['name']<=>b['name']}
+11
source

You can sort by key, just know if the key is a string or character at the same time.

@friends.sort_by { |f| f['name'] }

, :

@friends.sort_by { |f| f['name'].downcase }

, , !, @friends

>> @friends.sort_by! { |f| f['name'] }
>> @friends # now returns the sorted array of hashes
+7

All Articles