← Blog

Rails 7 adds Enumerable#maximum

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.

=> Item = Struct.new(:price)
=> items = [Item.new(12), Item.new(8), Item.new(24)]

=> items.map { |x| x.price }.max
=> 24

=> items.map { |x| x.price }.min
=> 8

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

=> items.maximum(:price)
=> 24

=> items.minimum(:price)
=> 8

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

# Before Rails 7

def index
  @items = Item.limit(20).to_a
  fresh_when @items, last_modified: @items.pluck(:updated_at).max
end

# After Rails 7

def index
  @items = Item.limit(20).to_a
  fresh_when(@items)
end

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.

Ashik Salman avatar
Written byAshik Salman
Newsletter

Stay up to date with our blogs.

Subscribe to receive an email notification for a new blog post.