Home > front end >  Why in Ruby Object's singleton_class isn't Class?
Why in Ruby Object's singleton_class isn't Class?

Time:12-31

I am a little confused, why is the super class of the singleton class using is_a? method but return false?

I

class Animal
end

obj = Animal.new
singleton = (class<<obj;self;end)

p singleton.ancestors , singleton.is_a?(Animal) 

#[#<Class:#<Animal:0x00000000060105d0>>, Animal, Object, Kernel, BasicObject]
#false

I think it shall return true.

Experienced experts please help me

CodePudding user response:

You are asking whether the singleton class is an animal. But the singleton class is not an animal, it is a class, i.e. it is an instance of the Class class, not the Animal class.

This is no different from any other class. For example 1 is an instance of Integer, but Integer is not an instance of Numeric, it is an instance of Class. Integer.is_a?(Numeric) would be false, since Integer is not an instance of Numeric, it is a subclass of Numeric.

  • Related