Open In App

Find maximum array element in Ruby

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:  






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






# 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  




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

Output: 

6 

Article Tags :