rringler
rringler

Reputation: 61

Ruby Instance Variable Syntax

I'm finishing The Well Grounded Rubyist and I've noticed some instance variable calls that I don't quite understand. Straight from TWGR (Section 15.2.2):

class Person
  attr_reader :name
  def name=(name)
    @name = name
    normalize_name
  end

  private
  def normalize_name
    name.gsub!(/[^-a-z'.\s]/i, "")
  end
end

Is the name variable in the normalize_name method an implicit instance variable? Would @name.gsub!(/[^-a-z'.\s]/i, "") have worked just as well? Is there some convention I should be aware of?

Upvotes: 0

Views: 209

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

Is the name variable in the normalize_name method an implicit instance variable?

No, it's not an instance variable. Instance variables start with an @ sigil, this doesn't, ergo, it cannot possibly be an instance variable. In fact, it's not a variable at all, it's a message send.

Upvotes: 0

coreyward
coreyward

Reputation: 80041

What's happening in normalize_name is that name resolves to the method self.name, which is defined by the attr_reader class macro at the top of the class. If you were to use attr_accessor instead, the name= method would be defined as well (but it wouldn't include the call to normalize_name.

These getter and setter methods automatically access instance variables. The name method defined by attr_accessible :name looks like this, essentially:

def name
  @name
end

Upvotes: 2

Related Questions