Ruby | Enumerable sort_by() function
Last Updated :
05 Dec, 2019
The sort_by() of enumerable is an inbuilt method in Ruby sorts enum using a set of keys generated by mapping the values in enum through the given block. The returned result is not guaranteed to be stable, it is unstable when the comparison is equal. It returns an enumerator when no block is given.
Syntax: enu.sort_by { |obj| block }
Parameters: The function accepts a block.
Return Value: It returns the an array.
Example 1:
enu = [ 10 , 14 , 22 , 19 ]
enu.sort_by {|obj| obj% 10 + (obj/ 10 )% 10 }
|
Output:
[10, 22, 14, 19]
Example 2:
enu = [ 10 , 14 , 22 , 19 ]
enu.sort_by
|
Output:
Enumerator: [10, 14, 22, 19]:sort_by
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...