Rails 7
adds
Enumerable#maximum and Enumerable#minimum to easily calculate the maximum or minimum from
extracted elements of an enumerable.
Let’s say we have a model called Product with an attribute price.
# app/models/product.rb
class Product < ApplicationRecord
attr_reader :price
endNow we need to get the maximum or minimum value of price for an array of products.
Before
We would get the minimum and maximum value using:
products = [Product.new(price: 20), Product.new(price: 33), Product.new(price: 22)]
minimum = products.pluck(:price).min # => 20
maximum = products.pluck(:price).max # => 33In the case of an ActiveRecord Collection, we could achieve this just by using
maximum and minimum directly on the collection as these methods are defined
in the ActiveRecord::Calculations library.
After
Rails 7 added maximum and minimum methods in the Enumerable module.
Hence they can be used directly on all enumerable.
So from the above example,
products = [Product.new(price: 20), Product.new(price: 33), Product.new(price: 22)]
minimum = products.minimum(:price) # => 20
maximum = products.maximum(:price) # => 33This is a simple enhancement, but it helps a lot when we have to deal with enumerable directly and not ActiveRecord Collection objects.
