What's the difference between @title
and title
? Since both of them can be variable names. Also, how do I decide which kind of variable I should use? With @
or not?
A variable is a name that Ruby associates with a particular object. For example: city = "Toronto" Here Ruby associates the string "Toronto" with the name (variable) city. Think of it as Ruby making two tables. One with objects and another with names for them.
Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.
title
is a local variable. They only exists within its scope (current block)
@title
is an instance variable - and is available to all methods within the class.
You can read more here: http://strugglingwithruby.blogspot.dk/2010/03/variables.html
In Ruby on Rails - declaring your variables in your controller as instance variables (@title
) makes them available to your view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With