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.
ruby
Output:
ruby
Output:
Syntax: enu.sort_by { |obj| block } Parameters: The function accepts a block. Return Value: It returns the an array.Example 1:
# Ruby program for sort_by method in Enumerable
# Initialize
enu = [10, 14, 22, 19]
# Prints
# sorts by addition of digits
enu.sort_by {|obj| obj%10 + (obj/10)%10}
[10, 22, 14, 19]Example 2:
# Ruby program for sort_by method in Enumerable
# Initialize
enu = [10, 14, 22, 19]
# Prints
enu.sort_by
Enumerator: [10, 14, 22, 19]:sort_by