开发者

class Class - instance vs. class methods

开发者 https://www.devze.com 2023-04-10 02:02 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号