1

I want to sort hash by position, I am using sort_by but it is not sorting out, as it should

hash = {
"a": {"name": "a", "type": "text", "position": 1, "required": "false"},
"b": {"name": "b", "type": "text", "position": 4, "required": "false"},
"c": {"name": "c", "type": "text", "position": 2, "required": "false"},
"d": {"name": "d", "type": "text", "position": 3, "required": "false"}
}

to sort this I am using following command

temp = hash.sort_by { |k,v| k[0]['position'] }

There is no error but I am getting save above hash without any sorting. Even I am using temp to create new hash and but it is same. where I want to it should be sorted by position 1,2,3,4. It is part of Ruby on Rails where I am creating these fields.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Kamal Panhwar
  • 2,345
  • 3
  • 21
  • 37

1 Answers1

4

sort_by is called with two arguments, k and v which refer to the entry's key and value.

Since you want to sort by position, you have to use v[:position]:

hash.sort_by { |k, v| v[:position] }
#=> [[:a, {:name=>"a", :type=>"text", :position=>1, :required=>"false"}],
#    [:c, {:name=>"c", :type=>"text", :position=>2, :required=>"false"}],
#    [:d, {:name=>"d", :type=>"text", :position=>3, :required=>"false"}],
#    [:b, {:name=>"b", :type=>"text", :position=>4, :required=>"false"}]]
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • Interesting I tried it but in my postgres JSONB it was not working so I was using array notations, now I realized I have to convert first to hash and then run above command. Thanks for helping out. Love your city Bremen. – Kamal Panhwar Feb 15 '21 at 09:32