Topic: Syntax is confusing. Where do I use :, @, so on
OK so I'm reading the Agile Rails Development book.
In Ruby I understand @ is an instance variable. The thing that gets really confusing is where the book goes into how Rails does everything magically for you and allows you to throw around variable names.
So in the controller I have a method calling a view and set an instance variable like @cart.
Then in the view, I always get confused. Some places they reference the cart variable like :cart. Other places it's @cart I think... As I understand this isn't part of Ruby. This is Rails "magically" throwing around variable names so that in one place it needs to be a variable with a : preceeding it which means something along the lines of "Thing named whatever". Then things preceeded by the @ refer directly to the instance variable created in the function. I'm a little confused where each correct format of variable goes.
Also how does the scope of the variable work? If I create the variable in a method of a controller I know it should be visible in the corresponding view template. Is it also visible to other methods in the controller? It's clearer in Java for example when you explicitly declare a variable in each method and see that it's newly created, and also I know the scope rules in Java, but here I don't know whether or not a variable is already in existence or what? I've gone through some ruby tutorials and I can't really find a great description about scope. It would really help me understand what's going on. Also if I call the controller method again is the variable still visible or is it a new instance of that variable and the old one will get cleaned by the garbage collector?
Like if I do this:
if(@var == nil)
@var = 34
I call method_1 and it creates @var with value 34. Then the second time will @var have a value of 34 or will it be nil again?
And will @var be visible to method_2 in this situation if method_1 is called first?
@var = 34
Last edited by ill (2009-06-26 17:03:24)