user1735921 user1735921 - 3 months ago 25
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

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
class for such purposes?


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