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.

1=> list = ["Sole Element"]
2=> list.sole
3=> "Sole Element"
4
5=> hash = { foo: "bar" }
6=> hash.sole
7=> [: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.

1=> list = [nil]
2=> list.sole
3=> nil
4
5=> list = []
6=> list.sole
7=> `Enumerable::SoleItemExpectedError (no item found)`
8
9=> list = ["Apple", "Orange"]
10=> list.sole
11=> `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.