lib/extensions/enumerable.rb in extensions-0.5.0 vs lib/extensions/enumerable.rb in extensions-0.6.0
- old
+ new
@@ -165,9 +165,76 @@
end
end
#
+# * Enumerable#none?
+#
+ExtensionsProject.implement(Enumerable, :none?) do
+ module Enumerable
+ #
+ # Enumerable#none? is the logical opposite of the builtin method Enumerable#any?. It
+ # returns +true+ if and only if _none_ of the elements in the collection satisfy the
+ # predicate.
+ #
+ # If no predicate is provided, Enumerable#none? returns +true+ if and only if _none_ of the
+ # elements have a true value (i.e. not +nil+ or +false+).
+ #
+ # [].none? # true
+ # [nil].none? # true
+ # [5,8,9].none? # false
+ # (1...10).none? { |n| n < 0 } # true
+ # (1...10).none? { |n| n > 0 } # false
+ #
+ def none? # :yield: e
+ if block_given?
+ not self.any? { |e| yield e }
+ else
+ not self.any?
+ end
+ end
+ end
+end
+
+
+#
+# * Enumerable#one?
+#
+ExtensionsProject.implement(Enumerable, :one?) do
+ 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
+end
+
+
+#
# * Object.in?
# This has special treatment: it's included here and in object.rb, so we don't
# want a warning if it's alredy defined.
#
unless Object.method_defined?(:in?)