Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add Enumerable#exclude? to bring parity to Enumerable#include? and av…

…oid if !x.include?/else calls [DHH]
  • Loading branch information...
commit 7b61541ea53c309847753d5553baa2eed9cc6282 1 parent 5f8e48c
@dhh dhh authored
View
2  activesupport/CHANGELOG
@@ -1,5 +1,7 @@
*Edge*
+* Add Enumerable#exclude? to bring parity to Enumerable#include? and avoid if !x.include?/else calls [DHH]
+
* Update Edinburgh TimeZone to use "Europe/London" instead of "Europe/Dublin" #3310 [Phil Ross]
* Update bundled TZInfo to v0.3.15 [Geoff Buesing]
View
5 activesupport/lib/active_support/core_ext/enumerable.rb
@@ -101,6 +101,11 @@ def many?(&block)
size = block_given? ? select(&block).size : self.size
size > 1
end
+
+ # The negative of the Enumerable#include?. Returns true if the collection does not include the object.
+ def exclude?(object)
+ !include?(object)
+ end
end
class Range #:nodoc:
View
5 activesupport/test/core_ext/enumerable_test.rb
@@ -89,4 +89,9 @@ def test_many
assert ![ 1, 2 ].many? {|x| x > 1 }
assert [ 1, 2, 2 ].many? {|x| x > 1 }
end
+
+ def test_exclude?
+ assert [ 1 ].exclude?(2)
+ assert ![ 1 ].exclude?(1)
+ end
end

8 comments on commit 7b61541

@robbyrussell

You'd wonder why this wasn't just part of Ruby. ;-)

@Bounga

Great addition

@duff

I dig it.

@spp

Thanks for making this popular, I was already using it for a while, after drawing inspiration from the whole Core Extension module of Rails.

@kamk

I also like:

object.in?(collection)
object.not_in?(collection)

@dubek

Actually, I disagree. On the same basis you should add invalid? to ActiveRecord, not_ssl? to the Request class etc. Ruby has a very short not operator (!) -- why not use it?

Yes, I know that ruby has "select" and "reject" which can be defined one using the other; still I think these are somewhat OK whereas "exclude?" (which is really "not_include?") is not needed.

@dtrasbo

dubek,

One of the major things that makes Ruby cool is readability, and the addition of Enumerable#exclude? certainly makes for more readability, and it does something we need all the time.

@rfunduk

Seems to me that unless x.include?( obj ) is actually more clear in this case... but no harm done.

Please sign in to comment.
Something went wrong with that request. Please try again.