4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ruby】is_a? と instance_of? の違い

Last updated at Posted at 2020-11-01

Mac で試せる

irb

前提

module ParentModule; end
module ChildModule; end

class ParentClass
  include ParentModule
end

class ChildClass < ParentClass
  include ChildModule
end

child_instance = ChildClass.new

is_a?メソッド

child_instance.is_a? ChildClass #=> true
child_instance.is_a? ParentClass #=> true
child_instance.is_a? Object #=> true
child_instance.is_a? String #=> false
child_instance.is_a? ParentModule #=> true
child_instance.is_a? ChildModule #=> true
  • is_a?メソッドがTrueを返す場合
    レシーバが引数の

    • クラスの直接のインスタンス、もしくは、
    • そのサブクラスのインスタンス、もしくは、
    • モジュールをインクルードしたクラス、もしくは、
    • そのサブクラスのインスタンスであれば、trueを返す
      (is_a の意味は、is one of ~ の意味なのかもしれない)

instance_of? メソッド

child_instance.instance_of? ChildClass #=> true
child_instance.instance_of? ParentClass #=> false
child_instance.instance_of? Object #=> false
child_instance.instance_of? String #=> false
child_instance.instance_of? ParentModule #=> false
child_instance.instance_of? ChildModule #=> false
  • instance_of?メソッドがTrueを返す場合
    • レシーバが引数で指定されたクラスの直接のインスタンスの場合、trueを返す
4
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?