{

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 value
  • Array.max: Returns Maximum value
  • Enumerable.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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to print the name of a Ruby class| Ruby on Rails By Example

How to check if the variable is defined in Ruby with examples

How to Generate Random number in Ruby with examples

How to Get current Unix timestamp or milliseconds since epoch Ruby Programming| Ruby on Rails by Example