Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.min() in Ruby?

okwudili onyejiaku

Overview

In Ruby, array.min() helps find the element with the minimum value. min() can return a number of elements with minimum values if n is passed as an argument.

Syntax

array.min()
# OR if "n" is specified
array.min([n])

Parameters

[n] (optional): [n] is used when you want to return nn number of elements with the highest or minimum values.

Return value

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

Example

In the example below, we create some arrays and use the min() method to find the minimum values.

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

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

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring