Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ variables in Ruby on Rails

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?

like image 211
OneZero Avatar asked Jan 14 '13 13:01

OneZero


People also ask

What is a variable in Ruby?

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.

How do I use a variable in Ruby?

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.

What is class variable and instance variable in Ruby?

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.


1 Answers

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.

like image 173
Peter Rasmussen Avatar answered Oct 16 '22 00:10

Peter Rasmussen