Ruby方法参数和访问器方法可以使用相同的名称吗?
比如说我上过这样的课:Ruby方法参数和访问器方法可以使用相同的名称吗?,ruby,Ruby,比如说我上过这样的课: class Parser attr_accessor :config, :html def initialize(config, html) @config = config @html = html end ... end class Parser attr_accessor :config, :html def initialize(config, html) self.config = config self
class Parser
attr_accessor :config, :html
def initialize(config, html)
@config = config
@html = html
end
...
end
class Parser
attr_accessor :config, :html
def initialize(config, html)
self.config = config
self.html = html
end
...
end
将初始化器方法的参数命名为与attr_访问器相同的名称安全吗?这是坏风格吗?什么样的款式更好?是的,很安全
Ruby实现了词法范围,并且有许多范围限定符
我想这是一种相当合理的款式。这个问题总是有点难回答,因为在某些方面代码更容易阅读(变量有最好的名称选择),在某些方面更难,因为给定的名称意味着两个不同的对象,这取决于它的使用位置。这样做是完全安全的,我一直都这样做。但是,我认为这样设置对象属性更好:
class Parser
attr_accessor :config, :html
def initialize(config, html)
@config = config
@html = html
end
...
end
class Parser
attr_accessor :config, :html
def initialize(config, html)
self.config = config
self.html = html
end
...
end
执行此操作时,代码将使用attr_acessor提供的setter方法。通过这种方式,访问变量的方式总是一致的。您对什么说“是”?(回复:“安全吗…”或回复:“款式不好吗?”)“是的”,“不是”,“这真的是你的选择。”:-)