slindsey3000
slindsey3000

Reputation: 4301

class Class - instance vs. class methods

How is it that this works? When the following is run "hi from class" is printed twice. What is going on inside ruby to make this behave like this? Am I NOT in fact making an instance method for class

class Class
  def foo
    puts "hi from class" 
  end
end

Class.foo
x = Class.new
x.foo

Upvotes: 6

Views: 226

Answers (1)

sepp2k
sepp2k

Reputation: 370455

I don't know whether you're aware of that, but when you do class Class ... end, you're not creating a new class named Class, you're reopening the existing class Class.

Since Class is the class that all classes are instances of that means that Class is an instance of itself. And because of that you can call any instance methods of Class directly on Class the same way you can on any other class.

Upvotes: 9

Related Questions