Skip to content
Related Articles

Related Articles

Improve Article

Find maximum array element in Ruby

  • Last Updated : 13 Sep, 2021

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 



My Personal Notes arrow_drop_up
Recommended Articles
Page :