Rails 7
Enumerable set to implement maximum and minimum methods

Mar 24, 2021

Rails 7 adds Enumerable#maximum and Enumerable#minimum methods to easily calculate the maximum or minimum from extracted elements. These methods have existed in ActiveRecord for some time now and is useful when you have a collection of records.

But in scenarios were you deal with a mix of collections and other enumerables, you might have had to use a mixture of map(:value).max or a custom inject/reduce implementation.

Given a model called Movie with an attribute rating.

 # app/models/movie.rb
class Movie < ApplicationRecord
  attr_reader :rating
end

If we wanted to get the maximum or minimum rating for an array of movies, we would previously have had to resort to something like this

movies = [
  Movie.new(rating: 1),
  Movie.new(rating: 5),
  Movie.new(rating: 9),
]
movies.pluck(:rating).min # => 1
movies.pluck(:rating).max # => 9

But with this update coming in Rails 7, we could achieve the same thing the same way we would have used on a collection

So from the above example,

movies = [
  Movie.new(rating: 1),
  Movie.new(rating: 5),
  Movie.new(rating: 9),
]
movies.minimum(:rating) # => 1
movies.maximum(:rating) # => 9

 # Just like an ActiveRecord scope
Movie.where(genre: :scifi).maximum(:rating)

Thank you for reading and Happy Coding!