Ruby | Enumerable sort() function

The sort() of enumerable is an inbuilt method in Ruby returns an array which contains the enum items in a sorted order. The comparisons are done using operator or the optional block. The block must implement a comparison between a and b and return an integer less than 0 when b follows a, 0 when a and b are equivalent, or an integer greater than 0 when a follows b. The result returned is not stable. The order of the element is not stable when the comparison of two elements returns 0.

Syntax: enu.sort { |a, b| block }

Parameters: The function accepts an optional comparison block.



Return Value: It returns the an array.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for sort method in Enumerable
  
# Initialize 
enu = (1..10)
  
# Prints
enu.sort 

chevron_right


Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for sort method in Enumerable
  
# Initialize 
enu = [10, 9, 8, 12, 10, 13]
  
# Prints
enu.sort {|a, b| a <=> b}

chevron_right


Output:

[8, 9, 10, 10, 12, 13]



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.