对Ruby中的类继承以及对self的多个引用感到困惑
我试图解构ruby gem,以便更好地理解ruby中的Oop。在大多数情况下,我确实可以看到继承和使用模块作为名称空间等的好处。我不确定我是否得到了额外的好处,我在想,也许在规模上,在我的本地机器上有一些我无法理解的好处。例如 这个代码对Ruby中的类继承以及对self的多个引用感到困惑,ruby,oop,Ruby,Oop,我试图解构ruby gem,以便更好地理解ruby中的Oop。在大多数情况下,我确实可以看到继承和使用模块作为名称空间等的好处。我不确定我是否得到了额外的好处,我在想,也许在规模上,在我的本地机器上有一些我无法理解的好处。例如 这个代码 module TestInheritance @testVariable = "" def self.configure yield @testVariable end end 这个密码呢 module TestInh
module TestInheritance
@testVariable = ""
def self.configure
yield @testVariable
end
end
这个密码呢
module TestInheritance2
@testVariable = ""
class << self
attr_accessor :testVariable
end
def self.configure
yield self.testVariable
end
end
moduletestinheritance2
@testVariable=“”
class这个问题的上下文非常有限;如果没有更多的用例,就没有理由更喜欢第二块代码而不是第一块。然而,有一个主要区别,可以在更完整的用例中发挥作用:
在第一个代码块中,testVariable
的值仅对TestInheritance
对象上的方法可用
在第二个代码块中,testVariable
的值通过方法TestInheritance2.testVariable
公开给其他调用者
下面是创建getter和setter方法的另一种更详细、更清晰的方法(其行为与第二段代码中的行为相同):
这个问题的背景非常有限;如果没有更多的用例,就没有理由更喜欢第二块代码而不是第一块。然而,有一个主要区别,可以在更完整的用例中发挥作用:
在第一个代码块中,testVariable
的值仅对TestInheritance
对象上的方法可用
在第二个代码块中,testVariable
的值通过方法TestInheritance2.testVariable
公开给其他调用者
下面是创建getter和setter方法的另一种更详细、更清晰的方法(其行为与第二段代码中的行为相同):
module TestInheritance2
@testVariable = ""
def self.testVariable
return @testVariable
end
def self.testVariable=(value)
@testVariable = value
end
end