Sha256: 02c023a874093a05795b4fecb02d6ee6226005cfa730068164d476c91abcc449
Contents?: true
Size: 1.31 KB
Versions: 26
Compression:
Stored size: 1.31 KB
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+). # # [].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 # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test require 'test/unit' class TCEnumerable < Test::Unit::TestCase def test_one? a = [nil, true] assert( a.one? ) a = [true, false] assert( a.one? ) a = [true, true] assert( ! a.one? ) a = [true, 1] assert( ! a.one? ) a = [1, 1] assert( ! a.one? ) end end =end
Version data entries
26 entries across 26 versions & 1 rubygems