How to Find the minimum and maximum values in an array and hash Ruby with examples
These tutorials show you how to find out the minimum and maximum values from an array.
How to find the minimum and maximum values from a given ruby
There are multiple ways used to find the min and max of a given array.
One way, using min and max methods in the Ruby array Another way using the Enumerable minmax method
Array.min
: Returns Minimum valueArray.max
: Returns Maximum valueEnumerable.minmax
: It returns an array of two values[min,max], First value is min and second value is max.
Here is
numbers=[11, 9, 58, 80]
# returns minimum number in array
puts numbers.min #returns 9
# returns maximum number in array
puts numbers.max #returns 80
# returns minimum and maximum number in array
puts numbers.minmax #returns 9 80
Output:
9
80
9
80
Find the minimum and maximum element from a Hash Object in Ruby?
The hash object contains keys and values.
If you want to find the min and max of a has values, How do you find them.
hash provides min_by
and max_by
methods to find min and max methods.
Here is an example
employees = {'frank' => 5000, 'Andrew' => 6000, 'Rocky' => 10000}
puts employees.min_by { |name, salary| salary } #=> ["frank", 5000]
puts employees.max_by { |name, salary| salary } #=> ["Rocky", 10000]
Output:
frank
5000
Rocky
10000
Conclusion
To Summarize, Learned Find min and max of the below objects
- Array
- Hash