Skip to content

Commit ebf69ab

Browse files
author
Tadas Tamošauskas
committed
Object#in? also accepts multiple parameters
1 parent 4cdd44e commit ebf69ab

File tree

2 files changed

+27
-7
lines changed

2 files changed

+27
-7
lines changed
Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,25 @@
11
class Object
2-
# Returns true if this object is included in the argument. Argument must be
3-
# any object which responds to +#include?+. Usage:
2+
# Returns true if this object is included in the argument(s). Argument must be
3+
# any object which responds to +#include?+ or optionally, multiple arguments can be passed in. Usage:
44
#
55
# characters = ["Konata", "Kagami", "Tsukasa"]
66
# "Konata".in?(characters) # => true
7+
#
8+
# character = "Konata"
9+
# character.in?("Konata", "Kagami", "Tsukasa") # => true
710
#
8-
# This will throw an ArgumentError if the argument doesn't respond
11+
# This will throw an ArgumentError if a single argument is passed in and it doesn't respond
912
# to +#include?+.
10-
def in?(another_object)
11-
another_object.include?(self)
12-
rescue NoMethodError
13-
raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
13+
def in?(*args)
14+
if args.length > 1
15+
args.include? self
16+
else
17+
another_object = args.first
18+
if another_object.respond_to? :include?
19+
another_object.include? self
20+
else
21+
raise ArgumentError.new("The single parameter passed to #in? must respond to #include?")
22+
end
23+
end
1424
end
1525
end

activesupport/test/core_ext/object/inclusion_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,16 @@
22
require 'active_support/core_ext/object/inclusion'
33

44
class InTest < Test::Unit::TestCase
5+
def test_in_multiple_args
6+
assert :b.in?(:a,:b)
7+
assert !:c.in?(:a,:b)
8+
end
9+
10+
def test_in_multiple_arrays
11+
assert [1,2].in?([1,2],[2,3])
12+
assert ![1,2].in?([1,3],[2,1])
13+
end
14+
515
def test_in_array
616
assert 1.in?([1,2])
717
assert !3.in?([1,2])

0 commit comments

Comments
 (0)