In what circumstances should instance variables be used in place of other types of variables?

I am using Ruby on Rails 3 and I would like to know under what circumstances should I use instance variables instead of other types of variables and if there is a security reason for them.

Example:

# Using an instance variable
@accounts = Account.find(...)

# Using a "local"\"normal" variable
account = Account.find(...)
+5
source share
2 answers

In the general case, an instance variable is local and stored inside an object instance, while a local variable is only local and stored inside a function / object / block area. For instance:

class User
  def name
    @name
  end

  def name= name
    @name = name
  end
end

def greet user
  name = user.name || 'John'
  p "Hi, my name is #{name}"
end

user = User.new
greet user
=> 'Hi, my name is John'
name
=> NameError: undefined local variable or method 'name' for main:Object
user.name = "Mike"
greet user
=> 'Hi, my name is Mike'
@name
=> nil

name , . , name = user.name || 'John', . name, NameError, .

@name User. , nil. local instance, nil, , .

, . @name , user.name , @name. name greet, , p "Hi, my name is #{name}", name, , .

+9

@Pan .

( ) . , -, , .

, , , .

-, , , , , .

( : Ruby 2 , , , Ruby. , .)

+9

All Articles