How to Find the Greatest Number in an Array of Numbers in Ruby?

In Ruby, you can find the greatest number in an array of numbers by using the Array#max method, for example, like so:

print [-1, 0, 1, 2.5, -7.5, 4].max #=> 4

When the list of numbers is empty, nil is returned:

print [].max #=> nil

If you would like to show the "n" number of the greatest numbers from the list, then you can do so by passing that number as an argument to the method. For example, to show two greatest numbers from a list, you would do the following:

print [-1, 0, 1, 2.5, -7.5, 4].max(2) #=> [4, 2.5]

In this instance, if the list of numbers is empty, then an empty array ([]) is returned:

print [].max(2) #=> []

Also, you can't pass a negative number as an argument to the method (as it would throw an ArgumentError):

# `max': negative size (-2) (ArgumentError)
print [-1, 0, 1, 2.5, -7.5, 4].max(-2)

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.