danynl danynl - 1 year ago 98
Ruby Question

ruby sort hashes within array in alphabetical order

I have an array of hashes and I want to sort the hashes in alphabetical order based on the value of the key :name

names_array = [{:name=>"item3",:ID=>"345"},{:name=>"item1",:ID=>"127"},{:name=>"item2",:ID=>"298"}]

the output should look like:

names_array = [{:name=>"item1",:ID=>"127"},{:name=>"item2",:ID=>"298"},{:name=>"item3",:ID=>"345"}]

Is there any way to this?

Answer Source
names_array.sort_by { |hash| hash[:name] }
#=> [{:name=>"item1", :ID=>"127"}, {:name=>"item2", :ID=>"298"}, {:name=>"item3", :ID=>"345"}]

See Enumerable#sort_by

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download