这两个 Ruby 类初始化定义有什么区别?
我正在阅读一本关于 Ruby 的书,作者使用了与本书前面部分略有不同的形式来编写类初始化定义。它看起来像这样:
class Ticket
attr_accessor :venue, :date
def initialize(venue, date)
self.venue = venue
self.date = date
end
end
在本书的前面部分中,它的定义如下:
class Ticket
attr_accessor :venue, :date
def initialize(venue, date)
@venue = venue
@date = date
end
end
使用第一个示例中的 setter 方法与第二个示例中使用实例变量之间是否有任何功能差异?他们似乎都工作。即使将它们混合起来也有效:
class Ticket
attr_accessor :venue, :date
def initialize(venue, date)
@venue = venue
self.date = date
end
end
I'm working through a book on Ruby, and the author used a slightly different form for writing a class initialization definition than he has in previous sections of the book. It looks like this:
class Ticket
attr_accessor :venue, :date
def initialize(venue, date)
self.venue = venue
self.date = date
end
end
In previous sections of the book, it would've been defined like this:
class Ticket
attr_accessor :venue, :date
def initialize(venue, date)
@venue = venue
@date = date
end
end
Is there any functional difference between using the setter method, as in the first example, vs. using the instance variable as in the second? They both seem to work. Even mixing them up works:
class Ticket
attr_accessor :venue, :date
def initialize(venue, date)
@venue = venue
self.date = date
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于setter方法是由attr_accessor定义的,因此除了设置变量之外什么也不做,所以使用setter方法和直接设置变量没有区别。
使用 setter 方法的唯一好处是,如果您稍后更改 setter 方法以执行除设置变量之外的其他操作(例如验证输入或记录某些内容),您的
initialize
方法将受到这些更改无需您进行更改。Since the setter method has been defined by
attr_accessor
and thus does nothing but setting the variable, there is no difference between using the setter method and setting the variable directly.The only upside to using the setter method is that if you should later change the setter method to do something more than setting the variable (like validate the input or log something), your
initialize
method would be affected by these changes without you having to change it.