user1735921 user1735921 - 18 days ago 7
Ruby Question

Ruby sort by hash and value

I have data like this:

hash_data = [
{:key1 => 'value4', :sortby => 4},
{:key1 => 'valuesds6', :sortby => 6},
{:key1 => 'valuedsd', :sortby => 1},
{:key1 => 'value2_data_is_here', :sortby => 2}
]


I want to sort it to this by the key
sortby


hash_data = [
{:key1 => 'valuedsd', :sortby => 1},
{:key1 => 'value2_data_is_here', :sortby => 2},
{:key1 => 'value4', :sortby => 4},
{:key1 => 'valuesds6', :sortby => 6}
]


I have tried using bubble sort, but is there any inbuilt function in a
Hash
class for such purposes?

Answer

Enumerable#sort_by to the rescue:

hash_data.sort_by { |hash| hash[:sortby] }
#=> [{:key1=>"valuedsd", :sortby=>1}, {:key1=>"value2_data_is_here", :sortby=>2}, {:key1=>"value4", :sortby=>4}, {:key1=>"valuesds6", :sortby=>6}]

If you don't care about initial object, I would suggest using Array#sort_by! to modify inplace - it is more resource-efficient:

hash_data.sort_by! { |hash| hash[:sortby] }

If you have different types of data as values to sortby key, you should first unify the data type and only then perform sorting.

To have array sorted in descending order, use Enumerable#reverse (or reverse!):

hash_data.sort_by {|hash| hash[:sortby] }.reverse
#=> [{:key1=>"valuesds6", :sortby=>6}, {:key1=>"value4", :sortby=>4}, {:key1=>"value2_data_is_here", :sortby=>2}, {:key1=>"valuedsd", :sortby=>1}]

Another option for sorting in descending order is the following - note minus sign (credits to @sagarpandya82):

hash_data.sort_by {|hash| -hash[:sortby] }
Comments