The array.max()
method in Ruby enables us to find the maximum value among elements of an array. It returns the element with the maximum value.
It can return more than one value by providing an extra argument that specifies how many elements to return.
array.max()
# when n is specified
array.max([n])
[n]
: This is an optional parameter for when you want to return n
number of elements with the highest values.The return value is an array that contains the maximum value or values if n
is specified.
In the code below, we create some arrays, and then find the maximum values using the max()
method.
# creating arrayslanguagesArray = ["Java", "C++", "Python", "Javascript", "Ruby on Rails!" ]numbersArray = [1, 2, 3, 4, 5]alphabetsArray = ["a", "b", "c", "d", "e"]booleanArray = [true, false]animalsArray = ["dog", "cat", "rat", "cow", "bat"]# get the max valuesa = numbersArray.max()b = languagesArray.max(2) # return 2 max valuesc = alphabetsArray.max(4) # return 4 max valuesd = animalsArray.max()# print max returned valuesputs "#{numbersArray}.max() = #{a}"puts "#{languagesArray}.max(2) = #{b}"puts "#{alphabetsArray}.max(4) = #{c}"puts "#{animalsArray}.max() = #{d}"
In the code above, the max()
method in line returns 5
because it is the greatest element in numbersArray
.
Similarly, in line , only two values are returned, which are "Ruby on Rails!"
and "Python"
. This is because the first letter of each of the two elements, "R"
and "P"
are actually greater in alphabetical order compared to the first letters of other elements.
In line , four values are returned based on the passed argument. This means that in alphabetical order, the highest four letters are "e", "d", "c", "b"
.
And lastly, in the same vein, when you compare the first letters of elements of animalsArray
, the greatest alphabetically is "r"
, which is why rat
was returned.