Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple instance_of?

Tags:

ruby

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
like image 790
RyanScottLewis Avatar asked Oct 24 '25 07:10

RyanScottLewis


2 Answers

[Foo,Bar].any? {|klass| my_foo.instance_of? klass}
like image 176
Ken Bloom Avatar answered Oct 26 '25 00:10

Ken Bloom


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
like image 34
Marc-André Lafortune Avatar answered Oct 26 '25 00:10

Marc-André Lafortune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!