How to Use the Ruby max_by Method

09/25/2021

Contents

In this article, you will learn how to use the Ruby max_by method.

Using the max_by method

The max_by method in Ruby is a built-in enumerable method that returns the maximum element of an enumerable object based on the block value returned for each element.

Here’s how you can use the max_by method in Ruby:

Start by creating an enumerable object that you want to find the maximum element of. This could be an array, hash, range, or any other object that implements the enumerable module.

numbers = [1, 5, 3, 7, 2, 8]

Use the max_by method on the enumerable object, and pass a block that returns a value for each element of the enumerable object.

max_number = numbers.max_by { |num| num }
puts max_number #=> 8

In the example above, the max_by method takes a block that returns each element of the numbers array. The max_by method then returns the element that has the maximum value.

You can also use max_by with more complex objects, and pass a block that accesses a specific attribute or property of each object.

class Person
  attr_accessor :name, :age
  def initialize(name, age)
    @name = name
    @age = age
  end
end

people = [
  Person.new("Alice", 25),
  Person.new("Bob", 30),
  Person.new("Charlie", 20)
]

oldest_person = people.max_by { |person| person.age }
puts oldest_person.name #=> "Bob"

In the example above, we define a Person class with a name and age attribute. We create an array of Person objects, and use the max_by method to find the oldest person in the array based on their age attribute.

If you want to find the n largest elements in an enumerable object, you can pass an integer argument to the max_by method.

largest_numbers = numbers.max_by(3) { |num| num }
puts largest_numbers #=> [8, 7, 5]

In the example above, we pass the integer argument 3 to the max_by method, which returns an array of the three largest elements in the numbers array.