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:
ruby
arr =[ 1 , 2 , 3 , 4 , 5 ].max
print arr
print "\n"
str1 = [ 1 , 2 , 3 , 4 , 5 ]
puts str1.max
print "\n"
str = [ "GFG" , "G4G" , "Sudo" , "Geeks" ]
print str.max
|
Output:
5
5
Sudo
Example #2:
ruby
def max(*arr)
arr.max
end
print max( 1 , 2 , 3 , 4 , 5 )
|
Output:
5
Example #3: A bit slower method
ruby
val = ( '1' .. '6' ).to_a.max
print val
|
Output:
6
Last Updated :
13 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...