这两个 Ruby 类初始化定义有什么区别?

发布于 2024-08-31 04:26:52 字数 609 浏览 3 评论 0原文

我正在阅读一本关于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冬天旳寂寞 2024-09-07 04:26:52

由于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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文