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?
What’s happening in
normalize_nameis thatnameresolves to the methodself.name, which is defined by theattr_readerclass macro at the top of the class. If you were to useattr_accessorinstead, thename=method would be defined as well (but it wouldn’t include the call tonormalize_name.These getter and setter methods automatically access instance variables. The
namemethod defined byattr_accessible :namelooks like this, essentially: