Using attr_writer to set instance variables in initialize

My coworker surprised me the other day and showed me how the standard “setter” methods can be used to set an instance variable in the initialize method of a class:

class Person
  def name=(name)
    @name = name
  end

  def initialize(name)
    self.name = name
  end
end

p Person.new("jerry")

When the attr_writer method is used, the code can be refactored as follows:

class Person
  attr_writer :name
  def initialize(name)
    self.name = name
  end
end

In the initialize() method, self.name = name calls the name() method, which sets the @name instance variable. I’m used to seeing explicit instance variable definitions in the initialize() method, but it makes sense that setter methods can be used as well. Here is how I usually see this type of code written (notice that the setter method is not used in initialize()):

class Person
  attr_writer :name
  def initialize(name)
    @name = name
  end
end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s