This blog is part of our Rails 7 series.
Rails 7 introduces the Enumerable#sole method, which can be used to find and
assert the presence of exactly one element in the enumerable.
The Enumerable#sole method is an add-on for
ActiveRecord::FinderMethods#sole
and
#find_sole_by
methods, which were recently added in Rails 6.1. Please check
our blog (Link is not available)
for more details on it.
=> list = ["Sole Element"]
=> list.sole
=> "Sole Element"
=> hash = { foo: "bar" }
=> hash.sole
=> [:foo, "bar"]
The Enumerable#sole method raises Enumerable::SoleItemExpectedError error if
the enumerable is empty or contains multiple elements. When the sole element is
nil, it will be returned as result.
=> list = [nil]
=> list.sole
=> nil
=> list = []
=> list.sole
=> `Enumerable::SoleItemExpectedError (no item found)`
=> list = ["Apple", "Orange"]
=> list.sole
=> `Enumerable::SoleItemExpectedError (multiple items found)`
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