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

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

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

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

print [].min #=> nil

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

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

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

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

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

# `min': negative size (-2) (ArgumentError)
print [-1, 0, 1, 2.5, -7.5, 4].min(-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.