Sorry if this may be a stupid question…
In my controller, what is the difference between doing:
total = 0
and
@total = 0
Thanks,
/mich
Sorry if this may be a stupid question…
In my controller, what is the difference between doing:
total = 0
and
@total = 0
Thanks,
/mich
In ruby, instance variables start with an @ and local variables don’t.
What this means in practice is if you want a variable in your controller
to be accessible in your view, you should be using an instance variable.
Jordan McKible wrote:
In ruby, instance variables start with an @ and local variables don’t.
What this means in practice is if you want a variable in your controller
to be accessible in your view, you should be using an instance variable.
Makes sense. Thanks for the clearification !
/mich
the scope of the variable.
when you create an @var, if will create a global variable, whereas a var
is a local variable => this means that if you create an action in your
controller (lets say:
def foo1
…
blahblah
@var = “something”
…
end
or alternitively,
def foo2
…
blahblah
var = “something”
end
in the view of foo1.rhtml you will be able to see the “something” string
by putting
<%= @var %>, whereas in the view of foo2.rhtml you would not be able to
use
<%= var %> - - if would give you an error like “undefined local
variable/method”
((same works for the view itself, say:
======view.rhtml ==========
<% for @var in @variables %>
…
<% end %>
<%= @var %> # the variable you want , will work, cause the scope of @
is a global one, not a ‘local’ one. . .
whereas:
========view.rhtml =========
<% for var in @variables %>
‘dies’ at the end statement.
<% end %>
======================
hope this helps somewhat. either way, reading some stuff off of
wiki.rubyonrails.com is a great resource.
later,
s
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs