本文介绍了Ruby:kind_of?与instance_of?与is_a?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别?我什么时候应该使用哪个?为什么会有这么多?

What is the difference? When should I use which? Why are there so many of them?

推荐答案

kind_of? is_a?是同义词。 instance_of?与其他两个不同之处在于,如果对象是该类的实例,它只返回 true ,而不是子类。

kind_of? and is_a? are synonymous. 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.

示例:hello.is_a?对象你好.kind_of?对象返回 true 因为hello String String Object 的子类。但是你好.instance_of?对象返回 false

Example: "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.

这篇关于Ruby:kind_of?与instance_of?与is_a?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 10:17