I am using Ruby on Rails 3 and I would like to know in what circumstances should I use instance variables instead of other variable types and if there are security reason for those.
Example:
# Using an instance variable
@accounts = Account.find(...)
# Using a "local"\"normal" variable
account = Account.find(...)
In general an instance variable is local and persisted inside an instance of an object, whereas a local variable is only local and persisted inside a function/object/block scope. For instance:
In the greet function
nameis a local variable that is only defined within that function. The name variable is set on the first line on the function,name = user.name || 'John', but its value is not persisted outside of the function. When you try callingnameyou get aNameErrorbecause name has only been defined as a local variable within the greet function.@nameis local to the user instance of the User class. When you try calling it outside of that context you getnil. This is one difference between local and instance variables, instance variables return nil if they have not been defined, whereas local non-instance variables raise an Error.Notice that both variable types are local to a specific context though.
@nameis defined within the user instance, so when you calluser.nameyou are calling the name function in the user instance, in which@nameis defined.nameis only defined in the greet function, so when you callp "Hi, my name is #{name}"you are able to get a value fornamebecause you are within the scope in which it is defined.