7

Rails 7 adds maximum and minimum methods to Enumerable

 3 years ago
source link: https://blog.saeloun.com/2021/03/17/rails-enumerable-maximum-and-minimum
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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
end

Now 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 # => 33

In 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) # => 33

This is a simple enhancement, but it helps a lot when we have to deal with enumerable directly and not ActiveRecord Collection objects.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK