How to Find the Maximum and Minimum Values in a Ruby Array

09/20/2021

Contents

In this article, you will learn how to get the maximum and minimum values in a Ruby Array.

Finding the Maximum and Minimum Values in an Array

In Ruby, you can easily find the maximum and minimum values in an array using the max and min methods, respectively.

Here’s an example:

arr = [5, 2, 9, 1, 7]

max_val = arr.max
min_val = arr.min

puts "Maximum value: #{max_val}"  # Output: Maximum value: 9
puts "Minimum value: #{min_val}"  # Output: Minimum value: 1

In this example, the max method returns the maximum value in the array arr, which is 9. Similarly, the min method returns the minimum value in the array, which is 1.

The max and min methods return nil if the array is empty. For example:

empty_arr = []

max_val = empty_arr.max
min_val = empty_arr.min

puts "Maximum value: #{max_val}"  # Output: Maximum value:
puts "Minimum value: #{min_val}"  # Output: Minimum value:

In this example, both max_val and min_val are nil because empty_arr has no elements.

You can also find the maximum and minimum values in an array using a block. The block should take two arguments and return -1, 0, or 1 depending on whether the first argument is less than, equal to, or greater than the second argument. Here’s an example:

arr = ["apple", "banana", "orange"]

max_len = arr.max { |a, b| a.length <=> b.length }
min_len = arr.min { |a, b| a.length <=> b.length }

puts "Longest element: #{max_len}"  # Output: Longest element: banana
puts "Shortest element: #{min_len}" # Output: Shortest element: apple

In this example, we use a block to compare the elements in arr based on their lengths, rather than their values. The max and min methods return the element with the longest and shortest lengths, respectively.