Rails 7 adds Enumerable#in_order_of

Ashik Salman

By Ashik Salman

on March 23, 2021

This blog is part of our  Rails 7 series.

Rails 7 introduces the Enumerable#in_order_of method, by which we can order and constrain any enumerable collection using a key-series pair.

1=> Item = Struct.new(:price)
2=> items = [Item.new(24), Item.new(32), Item.new(16)]
4=> items.in_order_of(:price, [16, 32, 24])
5=> [#<struct Item price=16>, #<struct Item price=32>, #<struct Item price=24>]

If any value in the series has no associated records in the enumerable collection, it will be ignored and the rest will be returned in the result.

1=> items.in_order_of(:price, (15..25))
2=> [#<struct Item price=16>, #<struct Item price=24>]

Similarly, any values not included in the series will be omitted from the final result.

1=> items.in_order_of(:price, [16, 32])
2=> [#<struct Item price=16>, #<struct Item price=32>]

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.