What's the Difference Between These Two Ruby Class Initialization Definitions?

若如初见. 提交于 2019-12-10 14:19:26

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/2751930/whats-the-difference-between-these-two-ruby-class-initialization-definitions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!