Why does the "I" in the "I" class belong to the class?

In the code below, the outputs are "I'm Thing".

class Thing
   class << self
      def foo
         puts "I am #{self}."
      end
   end
end

Thing.foo

I thought that “I” refers to an object of type Thing, but refers to a class of Thing. I gathered from a previous question (related in the comments) that this has something to do with Thing being an instance of Object. Is a block starting with the class <self actually executed in a context where the "I" refers to the Substance as an instance? What's going on here?

+4
source share
2 answers

Internally, a method selfrefers to an instance, inside a class / module definition, but outside of any method, to the class / module itself.

class Thing
  puts self.inspect
  def foo
    puts self.inspect
  end
end
puts "==="
Thing.new.foo

, , , , : , puts. puts "===" "===". , , .

+5

.

class Thing
   puts "self=#{self}"
   class << self
     puts "self in singleton class=#{self}"
     def foo
       puts "I am #{self}."
     end
   end
end
  # self=Thing
  # self in singleton class=#<Class:Thing>

Thing.foo
  # I am Thing.

, class << self class << Thing.

,

class Thing
end

class << Thing
   puts "self in singleton class=#{self}"
   def foo
     puts "I am #{self}."
   end
end
  # self in singleton class=#<Class:Thing>

Thing.foo
  # I am Thing.

class << self class << Thing : self Thing . , , Thing singleton class .

Yehuda Katz .

+4

Source: https://habr.com/ru/post/1659647/


All Articles