我如何让Object#instance_of?
接受多个参数,以便类似下面的例子?
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
答案 0 :(得分:8)
[Foo,Bar].any? {|klass| my_foo.instance_of? klass}
答案 1 :(得分:2)
如果你需要这样做一次,肯的回答是可行的。
[Foo,Bar].any? {|klass| my_foo.instance_of? klass}
如果你这样做几次,可能会有其他事情发生,即Foo
和Bar
之间的共性可以更明确:
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 :(得分:0)
您还可以使用alias_method_chain现有的instance_of?
实现来扩展它所需的功能:
>> 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