user1735921 user1735921 - 25 days ago 12
Ruby Question

Ruby sort by hash and value fast way

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 in built function for a Hash which can do this ?

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