0

I am looking for a solution to sort the Hash keys in an Array.

arr = [{"name"=>"Product Management", "id"=>647628}, {"name"=>"Sales", "id"=>647630}]

arr.each {|inner_hash| inner_hash.sort}

Expected Result:

[{"id"=>647628, "name"=>"Product Management"}, {"id"=>647630, "name"=>"Sales"}]
potashin
  • 44,205
  • 11
  • 83
  • 107

2 Answers2

2

you can use ruby Hash#sort_by to sort the elements of a Hash:

arr.map { |inner_hash| inner_hash.sort_by(&:first).to_h }
>> [{"id"=>647628, "name"=>"Product Management"}, {"id"=>647630, "name"=>"Sales"}]
uday
  • 1,421
  • 10
  • 19
2

Basically you don't need to sort hashes, but you can

arr.map { |h| h.sort.to_h }

# => [{"id"=>647628, "name"=>"Product Management"}, {"id"=>647630, "name"=>"Sales"}]
mechnicov
  • 12,025
  • 4
  • 33
  • 56