Tbpgr Blog

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

Ruby | Object | is_a? or kind_of?

概要

Object#is_a?(mod) -> bool
Object#kind_of?(mod) -> bool

詳細

オブジェクトが指定されたクラス mod かそのサブクラスのインスタンスであるとき真を返却

サンプルコード
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
parent.kind_of? Parent
child.kind_of? Parent
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

parent.instance_of? Parent # => true
child.instance_of? Parent  # => false
parent.is_a? Parent        # => true
child.is_a? Parent         # => true
parent.kind_of? Parent     # => true
child.kind_of? Parent      # => true