Ruby sort by hash and value -
i have data this:
hash_data = [ {:key1 => 'value4', :sortby => 4}, {:key1 => 'valuesds6', :sortby => 6}, {:key1 => 'valuedsd', :sortby => 1}, {:key1 => 'value2_data_is_here', :sortby => 2} ]
i want sort 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, there inbuilt function in hash
class such purposes?
enumerable#sort_by
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 don't care initial object, suggest using array#sort_by!
modify inplace - more resource-efficient:
hash_data.sort_by! { |hash| hash[:sortby] }
if have different types of data values sortby
key, should first unify data type , 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 sorting in descending order following - note minus sign (credits @sagarpandya82):
hash_data.sort_by {|hash| -hash[:sortby] }
Comments
Post a Comment