假设我有这样一个类:
class Parser
attr_accessor :config, :html
def initialize(config, html)
@config = config
@html = html
end
...
end
将初始化方法的参数命名为与 attr_accessors 相同的名称是否安全?风格不好吗?什么是更好的风格?
最佳答案
这样做是完全安全的,我也一直这样做。但是,我认为像这样设置对象属性是一种更好的样式:
class Parser
attr_accessor :config, :html
def initialize(config, html)
self.config = config
self.html = html
end
...
end
执行此操作时,您的代码将使用 attr_acessor 提供的 setter 方法。这样您就可以始终以一致的方式访问变量。
关于ruby - 可以为 Ruby 方法参数和访问器方法使用相同的名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4522070/