Ruby | Enumerable sort_by() function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

[10, 22, 14, 19]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.