How to Find Minimum Value in Array in Ruby
In Ruby, you can find the minimum value in an array using the
min method. Just call array.min on your array to get the smallest element.Syntax
The basic syntax to find the minimum value in an array is:
array.min: Returns the smallest element in the array.
This method works on arrays containing numbers, strings, or any objects that can be compared.
ruby
array = [5, 3, 9, 1, 7] min_value = array.min puts min_value
Output
1
Example
This example shows how to find the minimum number in a list of integers using min. It prints the smallest number.
ruby
numbers = [10, 20, 5, 15, 30] puts "The smallest number is: #{numbers.min}"
Output
The smallest number is: 5
Common Pitfalls
Some common mistakes when finding the minimum in an array include:
- Calling
minon an empty array returnsnil, which can cause errors if not handled. - Trying to find the minimum in an array with mixed data types (e.g., numbers and strings) will raise an error because Ruby cannot compare them.
Always ensure your array has comparable elements and is not empty before calling min.
ruby
empty_array = [] puts empty_array.min.nil? # true mixed_array = [1, "two", 3] # The following line will raise an error: # puts mixed_array.min
Output
true
Quick Reference
| Method | Description |
|---|---|
| array.min | Returns the smallest element in the array |
| array.min(n) | Returns an array of the n smallest elements |
| array.min_by { |x| block } | Returns the element with the minimum value from the block |
Key Takeaways
Use
array.min to get the smallest element in a Ruby array.Ensure the array is not empty to avoid getting nil or errors.
All elements must be comparable to use
min without errors.You can get multiple smallest elements with
min(n).Use
min_by to find the minimum based on a custom condition.