Devin Gray Devin Gray - 5 months ago 27
Ruby Question

Adding arrays of hashes and sort by hash value

I have two arrays

arrayOne = [{:name=>"name1", :id=>1}, {:name=>"name2", :id=>2}, {:name=>"name3", :id=>3}]

arrayTwo = [{:name=>"name2.1", :id=>1}, {:name=>"name2.2", :id=>2}, {:name=>"name2.3", :id=>3}]

And I want to flatten and sort these two arrays into one big array so I tried this

@bigArray = [arrayOne, arrayTwo].flatten.sort {|a,b| <=>}

However this does not work. I am new to rails and am unsure about the above
should it be mapped?
Is there a better way to do this?

(arrayOne + arrayTwo).sort_by { |e| e[:name] }
#=> [{:name=>"name2.1", :id=>1},
#    {:name=>"name2.1", :id=>1},
#    {:name=>"name2.2", :id=>2},
#    {:name=>"name2.2", :id=>2},
#    {:name=>"name2.3", :id=>3},
#    {:name=>"name2.3", :id=>3}]