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
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.
精彩评论