Open In App

Ruby | Enumerable sort_by() function

Improve
Improve
Like Article
Like
Save
Share
Report

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:




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


Output:

[10, 22, 14, 19]

Example 2:




# Ruby program for sort_by method in Enumerable
  
# Initialize 
enu = [10, 14, 22, 19]
  
# Prints 
enu.sort_by


Output:

Enumerator: [10, 14, 22, 19]:sort_by

Last Updated : 05 Dec, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads