Search code examples
ruby-on-railsrubysortingruby-hash

Can't sort hash tried few different ways


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.


Solution

  • 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"}]]