Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Object | instance_of?

概要

Object#instance_of?(klass) -> bool

詳細

オブジェクトがクラス klass の直接のインスタンスである時真を返却。

サンプルコード
require 'tbpgr_utils'

class Parent
end

class Child < Parent
end

parent = Parent.new
child = Child.new

bulk_puts_eval binding, <<-EOS
parent.instance_of? Parent
child.instance_of? Parent
parent.is_a? Parent
child.is_a? Parent
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

$ ruby object_instance_of.rb
parent.instance_of? Parent # => true
child.instance_of? Parent  # => false
parent.is_a? Parent        # => true
child.is_a? Parent         # => true