Ruby实例变量还是局部变量? [英] Ruby Instance Variables or Local Variables?
问题描述
我是Ruby语言的新手.我明白
I am new to Ruby language. I understand that
@@count: Class variables
@name: Instance variables
my_string: Local variables
我谨记以上几点.但是,我发现了一个这样的Ruby代码:
I keep the above in mind. However, I found one Ruby code like this:
class HBaseController < ApplicationController
...
def result
conn = OkHbase::Connection.new(host: 'localhost', port: 9090, auto_connect: true)
...
end
end
'conn'使我很困惑.
'conn' confuses me a lot.
"conn"是实例变量还是局部变量?那么"conn"的范围是什么?
Is 'conn' a instance variable, or local variable? And what is the scope of 'conn'?
推荐答案
我尝试用一个小例子来解释它:
I try to explain it with a little example:
class MyClass
def meth
conn = 1
end
def result
conn
end
end
x = MyClass.new
p x.result #-> test.rb:6:in `result': undefined local variable or method `conn'
conn
是未知的.让我们尝试先调用meth
:
conn
is unknown. Let's try to call meth
before:
class MyClass
def meth
conn = 1
end
def result
conn
end
end
x = MyClass.new
x.meth # try to create conn
p x.result #-> test.rb:6:in `result': undefined local variable or method `conn'
相同的结果.因此conn
是没有实例变量.您在meth
中定义了局部变量,但在外部它是未知的.
Same result. So conn
is no instance variable. You define a local variable in meth
but it is unknown outside.
让我们尝试使用实例变量:
Let's try the same with instance variables:
class MyClass
def meth
@conn = 1
end
def result
@conn
end
end
x = MyClass.new
p x.result #-> nil (no value assigned (*), but is is existing)
x.meth # initialze @conn with a value
p x.result #-> 1
使用访问器方法,您可以隐式定义一个实例变量:
With the usage of accessor-methods you define implicit an instance variable:
class MyClass
attr_reader :conn
def meth
conn = 1
end
def result
conn
end
end
x = MyClass.new
p x.result #-> nil (no value assigned (*), but is is existing)
x.meth # define conn with a value
p x.result #-> nil - the instance variable is not changed, a locale variable was used
在方法result
中,conn
是读取器方法conn
.在方法meth
中,它是一个区域设置变量(这可能会造成混淆,因为现在您拥有一个与变量同名的变量.
In method result
the conn
is the reader method conn
. In the method meth
it is a locale variable (this can be confusing, because now you have a variable with the same name as a variable.
如果要更改meth
方法中的conn
值,则必须定义一个setter并使用self.conn
:
If you want to change the conn
-value in the meth
-method you must define a setter and use self.conn
:
class MyClass
attr_reader :conn
attr_writer :conn
def meth
self.conn = 1
end
def result
conn
end
end
x = MyClass.new
p x.result #-> nil (not defined yet, but is is existing)
x.meth # define conn with a value
p x.result #-> 1
您可以将attr_reader
和attr_writer
替换为attr_accessor
.
(*)备注:我写了未分配值-这不是真的正确,nil
也是一个值.
(*) Remark: I wrote no value assigned - this is not really correct, nil
is also a value.
这篇关于Ruby实例变量还是局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!