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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With