3.3. Setter methods
When you need to set or change an object’s state at some point in your program other than the initialize method, the heart of the matter is assigning (or reassigning) values to instance variables. You can, of course, change any instance variable’s value in any method. For example, if we wanted tickets to have the ability to discount themselves, we could write an instance method like this inside the Ticket class definition:
def discount(percent) @price = @price * (100 - percent) / 100.0 end
But the most common case is the simplest: calling a setter method with an argument and setting the appropriate instance variable to the argument. That’s what set_name does in the Person class example.
There’s more to it, though. Ruby has ...
Get The Well-Grounded Rubyist, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.