tags:

views:

53

answers:

3

How would I make Object#instance_of? accept multiple arguments so that something like the below example would work?

class Foo; end
class Bar; end
class Baz; end

my_foo = Foo.new
my_bar = Bar.new
my_baz = Baz.new

my_foo.instance_of?(Foo, Bar) # => true
my_bar.instance_of?(Foo, Bar) # => true
my_baz.instance_of?(Foo, Bar) # => false
+4  A: 
[Foo,Bar].any? {|klass| my_foo.instance_of? klass}
Ken Bloom
I literally just figured that out as you answered =/ Thank you very much for the quick answer though!
c00lryguy
+2  A: 

If you need to do that once, Ken's answer is the way to go.

[Foo,Bar].any? {|klass| my_foo.instance_of? klass}

If you do this a couple of times though, there might be something else going on, i.e. a commonality between Foo and Bar that can be made more explicit:

module Foobarish; end
class Foo
  include Foobarish
end
class Bar
  include Foobarish
end
class Baz; end

Foo.new.kind_of? Foobarish # => true
Bar.new.kind_of? Foobarish # => true
Baz.new.kind_of? Foobarish # => false
Marc-André Lafortune
A: 

You can also alias_method_chain the existing instance_of? implementation to extend it with your desired functionality:

>> Object.class_eval do
>?   def instance_of_with_multiple_arguments(*arguments)
>>     arguments.any? { |klass| instance_of_without_multiple_arguments(klass) }
>>   end
>>
>>   alias_method :instance_of_without_multiple_arguments, :instance_of?
>>   alias_method :instance_of?, :instance_of_with_multiple_arguments
>> end
Evan Senter