6

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

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So what happens when (in the body of class Class) I def self.foo; puts "hi from **self**"; end; ... now the statement Class.foo prints hi from self?
@slindsey3000: If you define both an instance method and a class method on Class then Class.foo will call the class method and AnyOtherClass.foo will call the instance method. So in your example Class.foo will print hi from **self** and e.g. String.foo will print hi from class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.