0

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Would referencing the @name variable directly instead of the name method have worked? Is there an advantage to using the name method?
Yup. They do the same basic thing, but it's safer to use the getter — what if later down the line you decide to modify the data on read instead of on write?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.