Open In App

Ruby | Enumerable sort() function

Last Updated : 05 Dec, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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:




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


Output:

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

Example 2:




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


Output:

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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads