Trying to understand something about instance variables.

Kristen,

I think that the statement, "Instance variables only last till the
end of the method" is incorrect. Instance variables live as long as
their containing object lives. So, the Cart object has an instance
variable (an array) called @items. If your statement were true, there
would be no point in adding anything to it because @items would
disappear before anything useful can be done.

Here's what's going on starting with store_controller#add_to_cart:

1. You're creating a Cart object as a result of a find from the
database and calling it @cart. 2. Next, a Product object is created as a result of a find from the
database using an id parameter from the request. It's only a local
variable and it's called product. 3. The product is added to the @cart. 4. The controller method ends. By default, Rails looks for a .rhtml
file called /app/views/<controller>/<action>. By convention, store is
the controller name, and add_to_cart is the action name. 5. Presumably, you want to show what's in the cart in the view.
That's one reason why you're using an instance variable-- to make it
visible to the view. The local variable, product, is not available to
the view.

Hope it helps,

-Anthony

The decision about the visibility depends on the encapsulation principle in object oriented programming. The variables that you declare must have as minimal visibility as possible to get the job done. The reason is that this principle results in better quality software due to lower coupling.

You should read about basic OOP book if you are not familiar with basic concepts. Here is a some good books: Object Oriented Software Construction by Bertrand Meyer, Object Oriented Design Heuristics by Arthur J. Riel and if you want a freebie, my book available for free at http://guide.zepho.com/version1/