在什么情况下,我应该使用实例变量而不是其他变量类型? [英] In what circumstances should I use instance variables instead of other variable types?
问题描述
我使用Ruby on Rails 3,我想知道在什么情况下,我应该使用实例变量而不是其他变量类型,如果有安全的原因。
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.
示例:
# Using an instance variable
@accounts = Account.find(...)
# Using a "local"\"normal" variable
account = Account.find(...)
推荐答案
一般来说,实例变量是局部的,并且持久存在于对象的实例中,而局部变量只是局部变量, / object / block范围。例如:
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:
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
在greet函数 name
局部变量,只在该函数内定义。 name变量设置在函数的第一行, name = user.name || 'John'
,但是它的值不会在函数之外持久化。当您尝试调用 name
时,您会得到一个 NameError
,因为名称只在greet函数中被定义为一个局部变量。
In the greet function name
is 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 calling name
you get a NameError
because name has only been defined as a local variable within the greet function.
@name
对于User类的用户实例是本地的。当你尝试调用它之外的上下文,你会得到 nil
。这是局部和实例变量之间的一个区别,实例变量返回nil,如果它们没有被定义,而本地非实例变量引发错误。
@name
is local to the user instance of the User class. When you try calling it outside of that context you get nil
. 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.
注意,类型是特定上下文的本地。 @name
是在用户实例中定义的,所以当你调用 user.name
用户实例,其中定义了 @name
。 name
只定义在greet函数中,所以当你调用 pHi,我的名字是#{name}
您可以为 name
获取一个值,因为您在其定义的范围内。
Notice that both variable types are local to a specific context though. @name
is defined within the user instance, so when you call user.name
you are calling the name function in the user instance, in which @name
is defined. name
is only defined in the greet function, so when you call p "Hi, my name is #{name}"
you are able to get a value for name
because you are within the scope in which it is defined.
这篇关于在什么情况下,我应该使用实例变量而不是其他变量类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!