Sha256: 4ab627f8ff5ea244bfac8d5603be57b4bf7ab31437c403bcae8b11756bdee335

Contents?: true

Size: 981 Bytes

Versions: 6

Compression:

Stored size: 981 Bytes

Contents

module Enumerable

  unless method_defined?(:one?)  # 1.8.7+

    # 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+).
    #
    #   [].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
    #
    # CREDIT: Gavin Sinclair

    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

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
facets-2.8.4 lib/core/facets/enumerable/one.rb
facets-2.8.3 lib/core/facets/enumerable/one.rb
facets-2.8.2 lib/core/facets/enumerable/one.rb
facets-2.8.1 lib/core/facets/enumerable/one.rb
facets-2.8.0 lib/core/facets/enumerable/one.rb
facets-2.7.0 lib/core/facets/enumerable/one.rb