---
title: "Rails 7 adds Enumerable#sole"
description: "Rails 7.0 adds Enumerable#sole"
canonical_url: "https://www.bigbinary.com/blog/rails-7-adds-enumerable-sole"
markdown_url: "https://www.bigbinary.com/blog/rails-7-adds-enumerable-sole.md"
---

# Rails 7 adds Enumerable#sole

Rails 7.0 adds Enumerable#sole

- Author: Ashik Salman
- Published: April 27, 2021
- Categories: Rails, Rails 7

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](https://edgeapi.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-sole)
and
[#find_sole_by](https://edgeapi.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-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.

```ruby
=> 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.

```ruby
=> 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](https://github.com/rails/rails/pull/40914) for
more details.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-7-adds-enumerable-sole)
