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

Posted by michaelmichael on Stack Overflow See other posts from Stack Overflow or by michaelmichael
Published on 2010-05-01T23:35:00Z Indexed on 2010/05/02 18:18 UTC
Read the original article Hit count: 209

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about ruby

Related posts about instance-variables