Rails 7 adds Enumerable#sole

Ashik Salman

Ashik Salman

April 27, 2021

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.

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.