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

Finding the largest/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)

Hope you found this post useful. It was published . Please show your love and support by sharing this post.