instance method sole

Ruby on Rails 7.0.10

Since v7.0.10

Available in: v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

sole()

Returns the sole item in the enumerable. If there are no items, or more than one item, raises Enumerable::SoleItemExpectedError.

["x"].sole          # => "x"
Set.new.sole        # => Enumerable::SoleItemExpectedError: no item found
{ a: 1, b: 2 }.sole # => Enumerable::SoleItemExpectedError: multiple items found
Source
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 262
  def sole
    case count
    when 1   then return first # rubocop:disable Style/RedundantReturn
    when 0   then raise ActiveSupport::EnumerableCoreExt::SoleItemExpectedError, "no item found"
    when 2.. then raise ActiveSupport::EnumerableCoreExt::SoleItemExpectedError, "multiple items found"
    end
  end

Defined in activesupport/lib/active_support/core_ext/enumerable.rb line 262 · View on GitHub · Improve this page · Find usages on GitHub

Defined in Enumerable

Type at least 2 characters to search.

↑↓ navigate · open · esc close