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.
=> Item = Struct.new(:price)
=> items = [Item.new(24), Item.new(32), Item.new(16)]
=> items.in_order_of(:price, [16, 32, 24])
=> [#<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.
=> items.in_order_of(:price, (15..25))
=> [#<struct Item price=16>, #<struct Item price=24>]
Similarly, any values not included in the series will be omitted from the final result.
=> items.in_order_of(:price, [16, 32])
=> [#<struct Item price=16>, #<struct Item price=32>]
Check out this pull request for more details.

Written byAshik Salman
Related blogs
- 01Rails 7.1 allows subscribing to transaction eventsJanuary 16, 2024 · Vishnu M
- 02Rails 7.1 adds path_params option to url_forNovember 7, 2023 · Neenu Chacko
- 03Rails 7.1 optimizes the default SQLite3 configurationOctober 31, 2023 · Vishnu M
- 04Rails 7.1 adds multi-column ordering to batch processingOctober 3, 2023 · Navaneeth D