BigBinary Blog

We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.

Rails 7 adds Enumerable#sole

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 for more details on it.

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

Check out this pull request for more details.

Ashik Salman in Rails, Rails 7
April 27, 2021

Subscribe to our newsletter