basic Ruby question

hi all,

Understanding function has product = Product.find(params[:id]) and @cart = find_cart . Correct me if I'm wrong but I think you always need a @ before a variable? product hasn't got this. Does this mean product isn't a variable?

What is the difference between product and @cart.

Thanks Stijjn

def add_to_cart   product = Product.find(params[:id])   @cart = find_cart   @cart.add_product(product) end

Hi Stijjn,

Tarscher wrote:

What is the difference between product and @cart. def add_to_cart product = Product.find(params[:id]) @cart = find_cart @cart.add_product(product) end

product is a local variable. Its value is only available for use within the add_to_cart method. @cart is an instance variable. It's value is available for use within all the methods in the controller and their views for the duration of the request/response cycle in which the variable was instantiated.

hth, Bill


"product" is a local variable. It's scope is local to the method in
which it is being used. Once the method is finished executing,
"product" ceases to exist.

@cart is an instance variable. It's scope is the class in which it is
being used. If the add_to_cart method is defined in the controller,
then @cart will exist throughout the life of the controller. Instance
variables of controllers are accessible from the view. So, @cart
could be shown on a result page; "product" cannot.

I have two friendly suggestions born from my own experience learning
Rails. First, get a few Ruby-specific books. They will help with
these types of questions, act as references for functions, and the
more code you read from multiple sources, the better your code will
become. Second, in case add_to_cart from below is defined in your
controller, consider reading more about test driven development (TDD)
and try not to put business logic into the controller. Put business
logic in model objects and write unit tests for each model object. I
know it sounds like more work, but it will save you so much time
later on when you start modifying things.

Hope it helps,


You don't always need a @. In fact, you don't always need punctuation of any kind in Ruby! The @ makes the variable an instance variable. They can be used to share a value between different methods in the same class, such as inside one of your controllers in rails, or between a controller and its views.

Tarscher wrote:

product is a local variable @cart is an instance variable

On big difference for Rails has to do with the "magic" that injects the instance variables from a controller into the view being rendered. If this add_to_cart method is in a controller, the app/view/<controller>/add_to_cart.rhtml will have access to @cart, but not product.


Rob Biedenharn

thanks all for the quick replies!