Rails 7 adds Enumerable#maximum

Ashik Salman

By Ashik Salman

on February 23, 2021

This blog is part of our  Rails 7 series.

Rails 7 adds support for Enumerable#maximum and Enumerable#minimum to easily calculate the maximum and minimum value from a collection of enumerable elements.

Before Rails 7, we could only achieve the same results with a combination of map & max or min functions over the enumerable collection.

1=> Item = Struct.new(:price)
2=> items = [Item.new(12), Item.new(8), Item.new(24)]
4=> items.map { |x| x.price }.max
5=> 24
7=> items.map { |x| x.price }.min
8=> 8

This is simplified with Rails 7's newly-introduced maximum and minimum methods.

1=> items.maximum(:price)
2=> 24
4=> items.minimum(:price)
5=> 8

These methods are available through Action Controller's fresh_when and stale? for convenience.

1# Before Rails 7
3def index
4  @items = Item.limit(20).to_a
5  fresh_when @items, last_modified: @items.pluck(:updated_at).max
8# After Rails 7
10def index
11  @items = Item.limit(20).to_a
12  fresh_when(@items)

The etag or last_modified header values will be properly set here based on the maximum value of the updated_at field.

Check out this pull request for more details.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.