什么是本地范围? [英] what is local scope exactly?
问题描述
说实话,我还是对实例变量和局部变量一头雾水,不知道该用哪个.
我只知道一个不能使用的局部变量的条件是:
class MyClass定义初始化本地变量 = 1@instance_var = 1结尾def show_local_var本地变量结尾def show_instance_var@instance_var结尾结尾
显然,MyClass.new.show_instance_var
有效而 MyClass.new_show_local_var
无效
关于这两种变量的另一件事是块似乎共享相同的局部作用域,因此可以引用局部变量:
local_var = 13.次做放置 local_var结尾
关于这些区别,我知道的就这么多,还有其他可用的吗?请告诉我
如果有任何关于这方面的文章,那对我很有帮助,
局部变量用于此时此刻",无法从其他任何地方访问.
class MyClass定义 foolocal_var = 2#我用它来做某种计算@instance_var = local_var + 34local_var = 5 * @instance_var放置 local_var结尾# 从这里开始,local_var 是不可访问的.结尾
一旦你超出范围(foo
的 end
被传递)local_var
不再存在并且不能被引用.
实例变量在任何时候都可供全班使用.
class MyClass定义初始化@instance_var = 0结尾定义 foolocal_var = 2#我用它来做某种计算@instance_var = local_var + 34结尾def some_operation如果@instance_var == 36@instance_var = 3别的@instance_var = 1结尾结尾结尾
因此,当您调用 m = MyClass.new
以及稍后调用 m.some_operation
时,它会使用相同的 @instance_var
.>
虽然我们正在研究它,但还有一些类变量(定义的 @@class_var
)可以从类的任何实例访问.
我没有专门为您提供的文章,但是通过谷歌搜索有关 ruby 变量范围
和关于每种类型的变量的独立信息应该会为您提供您需要的所有信息!
To be honest, I still confused about the instance variable and local variable, not sure which should be used.
only one condition I know about local variable that can't be used is:
class MyClass
def initialize
local_var = 1
@instance_var = 1
end
def show_local_var
local_var
end
def show_instance_var
@instance_var
end
end
apparently, MyClass.new.show_instance_var
works while MyClass.new_show_local_var
not
the other thing about the two kind of variables is that the block seems share the same local scope, so the local variable can be referenced:
local_var = 1
3.times do
puts local_var
end
There are all I know about the distinctions, is there any other available? please let me know
if there is any articles about this, that would be so helpful for me,
A local variable is used "right here right now" and can't be accessed from anywhere else.
class MyClass
def foo
local_var = 2
#I use this to do some sort of calculation
@instance_var = local_var + 34
local_var = 5 * @instance_var
puts local_var
end
# From here, local_var is unaccessible.
end
Once you're out of scope (foo
's end
is passed) local_var
is no more and can't be referred to.
The instance variable is available to the whole class at all times.
class MyClass
def initialize
@instance_var = 0
end
def foo
local_var = 2
#I use this to do some sort of calculation
@instance_var = local_var + 34
end
def some_operation
if @instance_var == 36
@instance_var = 3
else
@instance_var = 1
end
end
end
So when you call m = MyClass.new
and later on m.some_operation
, it's working with the same @instance_var
.
And while we're at it, there are also Class variables (defined @@class_var
) that are accessible from any instance of the class.
I don't have an article in particular to provide you, but some googling about ruby variable scope
and about each type of variable independently should provide you with all the information you need!
这篇关于什么是本地范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!