Sha256: cea106c8652da8f4e40d27517895f9e3dd90dcc36b7514c3ba67ccd4f3b812b3

Contents?: true

Size: 925 Bytes

Versions: 4

Compression:

Stored size: 925 Bytes

Contents

#--
# Credit goes to Gavin Sinclair.
#++
module Enumerable
  #
  # Enumerable#one? returns +true+ if and only if <em>exactly one</em> element in the
  # collection satisfies the given predicate.
  #
  # If no predicate is provided, Enumerable#one? returns +true+ if and only if <em>exactly
  # one</em> element has a true value (i.e. not +nil+ or +false+).
  #
  #   require 'facet/enumerable/one?'
  #
  #   [].one?                      # false
  #   [nil].one?                   # false
  #   [5].one?                     # true
  #   [5,8,9].one?                 # false
  #   (1...10).one? { |n| n == 5 } # true
  #   (1...10).one? { |n| n < 5 }  # false
  #
  def one?  # :yield: e
    matches = 0
    if block_given?
      self.each do |e|
        if yield(e)
          matches += 1
          return false if matches > 1
        end
      end
      return (matches == 1)
    else
      one? { |e| e }
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
facets-0.6.3 lib/facet/enumerable/one?.rb
facets-0.7.0 lib/facet/enumerable/one%3F.rb
facets-0.7.1 lib/facet/enumerable/one%3F.rb
facets-0.7.2 lib/facet/enumerable/one%3F.rb