Trusted answers to developer questions
Trusted Answers to Developer Questions

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 99 returns 5 because it is the greatest element in numbersArray.

Similarly, in line 1010, 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 1111, 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
RELATED COURSES

View all Courses

Keep Exploring