在这个ruby示例中,.self的用法是什么?

我一直在读我的教科书,我们来上课,关键词self出现了。 我一直在阅读关于tutorialpoint的一些教程并阅读了一些SO问题,但由于某种原因它只是没有点击我的头部使用ruby Self ,所以我决定我会修补一些例子

考虑

 class Box # Initialize our class variables @@count = 0 def initialize(w,h) # assign instance avriables @width, @height = w, h @@count += 1 end def self.printCount() puts "Box count is : #@@count" end end # create two object box1 = Box.new(10, 20) box2 = Box.new(30, 100) # call class method to print box count Box.printCount() 

如果我们删除self.为什么我们会收到错误self. 从我们的printCount()方法? 我知道self对于区分类变量和实例变量非常重要,例如我的示例@width,@height@@count

所以我认为,因为我正在尝试修改类变量@@count ,所以我需要使用.self关键字,因为我正在尝试修改类变量。 因此,每当我们想要更改类变量时,我们必须使用def self.methodNameforms。

我的思维过程是否正确?

您在此处使用两种类型的方法:实例方法和类方法。 如您所知,Ruby是一种面向对象的编程语言,所以一切都是对象。 每个对象都有自己可以调用的方法。 我们来看看你的代码

 class Box # Initialize our class variables @@count = 0 def initialize(w,h) # assign instance avriables @width, @height = w, h @@count += 1 end def self.printCount() puts "Box count is : #@@count" end end 

使用self.method_name创建方法时,您将为类本身创建方法。 因此Box的对象有一个名为printCount()的方法。 这就是你可以直接调用该方法的原因。

 Box.printCount() 

但是,如果声明类Box的新实例,则调用printCount()将导致错误。

 box1 = Box.new(1,1) box1.printCount() #=> undefined method `printCount' 

这是因为box1Box类的一个实例,而printCount方法只能由Box类访问。

如果你在方法printCount之前删除self ,它将成为一个实例方法,然后box1将有权访问该方法,但是Box类不会。

还有一些语义,Ruby使用snake_case作为方法名,因此printCount应该是printCount 。 这只是标准做法,并不会真正影响代码的运行方式。

此外,您需要注意类变量,即@@count 。 它们的行为与您在Ruby中的预期不同。 它不仅属于它声明的类,它也是它的任何后代的一部分。

例如,假设我定义了一个新的类调用SmallBox并从Boxinheritance。

 box1 = Box.new(1,1) box1 = Box.new(1,1) 

现在, Box的计数应为2。 但是,如果您尝试从我的新class级访问@@count

 class SmallBox < Box p @@count end 

这也将打印2

来自后代的类变量的任何更改都将更改其值。

例如,我声明了一个SmallBox实例,它会在@@count加1。 您可以查看是否在Box查看了计数,它还添加了1。

 small1 = SmallBox.new(1,1) class SmallBox p @@count #=> 3 end class Box p @@count #=> 3 end