有什么不同?我应该什么时候使用哪个?为什么有这么多呢?
我也不会调用两个多(is_a?和kind_of?是同一方法的别名),但如果你想看到更多的可能性,将注意力转移到#class方法:
A = Class.new
B = Class.new A
a, b = A.new, B.new
b.class < A # true - means that b.class is a subclass of A
a.class < B # false - means that a.class is not a subclass of A
# Another possibility: Use #ancestors
b.class.ancestors.include? A # true - means that b.class has A among its ancestors
a.class.ancestors.include? B # false - means that B is not an ancestor of a.class
kind_of?并且is_a?是同义词。instance_of?与其他两个不同的是,只有true当对象是一个确切的类的实例,而不是子类时才会返回。
例如:"hello".is_a? Object和"hello".kind_of? Object返回true因为"hello"是String和String是它的一个子类Object。但是,"hello".instance_of? Object返回false。