Open In App

Find maximum array element in Ruby

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to find maximum array element in Ruby. There are multiple ways to find maximum array element in Ruby. Let’s understand each of them with the help of example. 
 

Example #1:  

ruby




# max function on list
arr =[1, 2, 3, 4, 5].max
print arr
print "\n"
 
 
str1 = [1, 2, 3, 4, 5]
puts  str1.max
print "\n"
 
# max function on string
str = ["GFG", "G4G", "Sudo", "Geeks"]
print str.max


Output: 

5
5
Sudo

Example #2:  

ruby




# Function to find the max using max method
def max(*arr)
 arr.max
end
 
print max(1, 2, 3, 4, 5)


Output:  

5

Example #3: A bit slower method  

ruby




# Using enumerable#max
val = ('1'..'6').to_a.max
print val


Output: 

6 


Last Updated : 13 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads