danynl danynl - 19 days ago 5x
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?

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

See Enumerable#sort_by