且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

红宝石:种类?与 instance_of 对比?vs. is_a?

更新时间:2023-08-21 18:35:16

kind_of?is_a? 是同义词.

instance_of? 与其他两个不同,它仅在对象是该类的实例而非子类时才返回 true.

instance_of? is different from the other two in that it only returns true if the object is an instance of that exact class, not a subclass.

示例:

  • "你好".is_a?Object"hello".kind_of?Object 返回 true 因为 "hello"StringString对象代码>.
  • 但是"hello".instance_of?对象返回false.
  • "hello".is_a? Object and "hello".kind_of? Object return true because "hello" is a String and String is a subclass of Object.
  • However "hello".instance_of? Object returns false.