Thursday, March 15, 2007

Using Setter method to change object state dynamically

The Setter method are methods defined at the end with an equal sign (=).
def price=(amount)
      @price = amount
end

you can then call it just like any other method:
ticket.price=(65.00)
或者使用syntactic sugar方式:
ticket.price = 65.00

When the interpreter sees the message “price” followed by “ =”, it automatically ignores the space before equal sign and reads the single message “price=”—a call to the method whose name is price=, which we’ve defined.
As for the right-hand side: parentheses are optional on single arguments to methods, so you can just put 65.00 there and it will be picked up as the argument to the price= method.

No comments: