nickackerman42 nickackerman42 - 1 month ago 6
Ruby Question

Why does self in "class << self" refer to the class?

The code below outputs "I am Thing."

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

Thing.foo


I thought "self" refers to an object of type Thing, but it refers to the class Thing. I have gathered from a previous question (linked in the comments) that this has something to do with the fact that Thing is an instance of Object. Is the block beginning with class << self actually executed in a context where "self" refers to Thing as an instance? What is going on here?

Answer

Inside methods self refers to the instance, inside 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

Try the code above and you’ll likely see what’s happening there: the class is being parsed in the first place, and the first puts is being executed. Then puts "===" prints the "===" string out. And, afterwards, the instance is being printed from inside the method.