Multiple copies?
How do I go about Object#instance_of?
taking multiple arguments so that something like the example below works?
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
+2
a source to share
3 answers
If you have to do it once, Ken's answer is the way to go.
[Foo,Bar].any? {|klass| my_foo.instance_of? klass}
If you do this multiple times, it is possible that something else will happen, i.e. there is 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
+2
a source to share
You can also use alias_method_chain to use an existing implementation instance_of?
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
0
a source to share