Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 622
michaelmichael Avatar asked May 01 '10 23:05

michaelmichael


People also ask

What is initialization in Ruby?

The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object. Below are some points about Initialize : We can define default argument. It will always return a new object so return keyword is not used inside initialize method.

Is initialize an instance method in Ruby?

new, allocate, and initialize You can call this method yourself to create uninitialized instances of a class. But don't try to override it; Ruby always invokes this method directly, ignoring any overriding versions you may have defined. initialize is an instance method.

What is def initialize?

verb. ini·​tial·​ize i-ˈni-shə-ˌlīz. initialized; initializing. transitive verb. : to set (something, such as a computer program counter) to a starting position, value, or configuration.


1 Answers

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.

like image 107
sepp2k Avatar answered Sep 27 '22 16:09

sepp2k