You want to let outside code set your objects' instance variables, but you also want to impose some control over the values your variables are set to. You might want a chance to validate new values before accepting them. Or you might want to accept values in a form convenient to the caller, but transform them into a different form for internal storage.
Define your own setter method for each instance variable you
want to control. The setter method for an instance variable
quantity would be called
quantity=. When a user issues a statement
object.quantity = 10, the
object#quantity= is called
with the argument 10.
It's up to the
method to decide whether the instance variable
quantity should actually take the value 10.
A setter method is free to raise an
ArgumentException if it's passed an invalid
value. It may also modify the provided value, massaging it into the
canonical form used by the class. If it can get an acceptable value,
its last act should be to modify the instance variable.
I'll define a class that keeps track of peoples' first and last names. It uses setter methods to enforce two somewhat parochial rules: everyone must have both a first and a last name, and everyone's first name must begin with a capital letter:
class Name # Define default getter methods, but not setter methods. attr_reader :first, :last # When someone tries to set a first name, enforce rules about it. def first=(first) if ...