Related Tags

array
ruby
communitycreator

# What is array.max() in Ruby?

okwudili onyejiaku

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.

fig 1: Calling array.max() on an array

### Syntax

array.max()
# when n is specified
array.max([n])


### Parameters

• [n]: This is an optional parameter for when you want to return n number of elements with the highest values.

### Return value

The return value is an array that contains the maximum value or values if n is specified.

### Code

In the code below, we create some arrays, and then find the maximum values using the max() method.

# creating arrays
languagesArray = ["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 values
a = numbersArray.max()
b = languagesArray.max(2)    # return 2 max values
c = alphabetsArray.max(4)    # return 4 max values
d = animalsArray.max()

# print max returned values
puts "#{numbersArray}.max() = #{a}"
puts "#{languagesArray}.max(2) = #{b}"
puts "#{alphabetsArray}.max(4) = #{c}"
puts "#{animalsArray}.max() = #{d}"

### Explanation

In the code above, the max() method in line $9$ returns 5 because it is the greatest element in numbersArray.

Similarly, in line $10$, 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 $11$, 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.

RELATED TAGS

array
ruby
communitycreator

CONTRIBUTOR

okwudili onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time