From 29383c2fe512bc807f5f0a018001d21fa8b28dd0 Mon Sep 17 00:00:00 2001 From: John Reitano Date: Fri, 21 Jan 2011 06:52:37 -0800 Subject: [PATCH] add Object#in? --- .../lib/active_support/core_ext/object.rb | 1 + .../lib/active_support/core_ext/object/in.rb | 27 ++++++++++++++++++++ activesupport/test/core_ext/object/in_test.rb | 20 ++++++++++++++ 3 files changed, 48 insertions(+), 0 deletions(-) create mode 100644 activesupport/lib/active_support/core_ext/object/in.rb create mode 100644 activesupport/test/core_ext/object/in_test.rb diff --git a/activesupport/lib/active_support/core_ext/object.rb b/activesupport/lib/active_support/core_ext/object.rb index 790a26f..a76815f 100644 --- a/activesupport/lib/active_support/core_ext/object.rb +++ b/activesupport/lib/active_support/core_ext/object.rb @@ -2,6 +2,7 @@ require 'active_support/core_ext/object/acts_like' require 'active_support/core_ext/object/blank' require 'active_support/core_ext/object/duplicable' require 'active_support/core_ext/object/try' +require 'active_support/core_ext/object/in' require 'active_support/core_ext/object/conversions' require 'active_support/core_ext/object/instance_variables' diff --git a/activesupport/lib/active_support/core_ext/object/in.rb b/activesupport/lib/active_support/core_ext/object/in.rb new file mode 100644 index 0000000..fb5b7c0 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object/in.rb @@ -0,0 +1,27 @@ +class Object + # This method tells you whether self is one of the method arguments. + # + # This simplifies: + # + # [1,2,3].include?(x) + # + # ...to: + # + # x.in?(1,2,3) + # + #....or: + # + # my_array = [1,2,3] + # x.in?(*my_array) + # + # which is a bit easier to read and write (at least in English) + # + def in?(*args) + args.include?(self) + end + + def not_in?(*args) + !in?(*args) + end +end + diff --git a/activesupport/test/core_ext/object/in_test.rb b/activesupport/test/core_ext/object/in_test.rb new file mode 100644 index 0000000..f34d6c4 --- /dev/null +++ b/activesupport/test/core_ext/object/in_test.rb @@ -0,0 +1,20 @@ +require 'active_support/core_ext/object/in' + +class ArrayInTests < Test::Unit::TestCase + def test_in? + assert_equal 3.in?(), false + assert_equal 3.in?(3), true + assert_equal 3.in?(4), false + assert_equal 3.in?(1,3), true + assert_equal 3.in?(1,4), false + end + + def test_not_in? + assert_equal 3.not_in?(), true + assert_equal 3.not_in?(3), false + assert_equal 3.not_in?(4), true + assert_equal 3.not_in?(1,3), false + assert_equal 3.not_in?(1,4), true + end +end + -- 1.7.3.5