Rails 7 adds Enumerable#maximum

Ashik Salman

Ashik Salman

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)]
3
4=> items.map { |x| x.price }.max
5=> 24
6
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
3
4=> items.minimum(:price)
5=> 8

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

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

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.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.