我注意到下面的代码局部变量语法正确:在红宝石一类
class Foo
bar = 3
end
现在,我知道,实例变量被@
访问,并通过@@
类变量,但我不能找出bar
存储在这种情况下或如何访问它。
我怎样才能找到bar
的范围?
我注意到下面的代码局部变量语法正确:在红宝石一类
class Foo
bar = 3
end
现在,我知道,实例变量被@
访问,并通过@@
类变量,但我不能找出bar
存储在这种情况下或如何访问它。
我怎样才能找到bar
的范围?
Ruby中的类的主体只是可执行的Ruby代码。这些确实是局部变量(不需要引号),并遵循“常规”规则作为局部变量。你可以在课堂上访问它们。如果你硬是要在那里bar
定义的范围,你可以使用Kernel.binding
:
class Foo
bar = 42
@@scope = binding
def self.scope
@@scope
end
end
Foo.scope.local_variables # => [:bar]
Foo.scope.local_variable_get(:bar) # => 42
一个需要注意的一点 - 使用def
变化范围,因此,他们不会使用def
定义可见里面的方法。
bar
变量将被访问,直到您关闭该类的定义。它不会在你定义的方法内被访问。
你可以尝试运行IRB代码:
$ irb
irb(main):001:0> class Test
irb(main):002:1> bar = 1
irb(main):003:1> puts bar
irb(main):004:1> end
1
=> nil
irb(main):005:0> puts bar
NameError: undefined local variable or method `bar' for main:Object
from (irb):5
from /usr/bin/irb:11:in `<main>'
irb(main):006:0> class Test
irb(main):007:1> puts bar
irb(main):008:1> end
NameError: undefined local variable or method `bar' for Test:Class
from (irb):7:in `<class:Test>'
from (irb):6
from /usr/bin/irb:11:in `<main>'
irb(main):009:0>
检查的实例方法的可用性:
irb(main):018:0> class Test
irb(main):019:1> bar = 1
irb(main):020:1> def test
irb(main):021:2> puts bar
irb(main):022:2> end
irb(main):023:1> end
=> :test
irb(main):024:0> a = Test.new
=> #<Test:0x00000000f447a0>
irb(main):025:0> a.test
NameError: undefined local variable or method `bar' for #<Test:0x00000000f447a0>
from (irb):21:in `test'
from (irb):25
from /usr/bin/irb:11:in `<main>'
类中的方法检查可用性:
irb(main):026:0> class Test
irb(main):027:1> bar = 1
irb(main):028:1> def self.test
irb(main):029:2> puts bar
irb(main):030:2> end
irb(main):031:1> end
=> :test
irb(main):032:0> Test.test
NameError: undefined local variable or method `bar' for Test:Class
from (irb):29:in `test'
from (irb):32
from /usr/bin/irb:11:in `<main>'
有没有办法“保存”这些声明?一种将它们传播到方法或其他东西的方法? –
@GiladNaaman:不会的。因此,名称_local_变量。 :) –
它可以从同一个班级机构访问。
class Foo
bar = 3
bar # => 3
end
据词法范围,所以它是一个块中访问:
class Foo
bar = 3
pr = ->{p bar}
pr.call # => 3
end
但是一旦类主体已关闭它甚至不是在同级别访问:
class Foo
bar = 3
end
class Foo
bar # => error
end
也不能从方法定义中访问:
class Foo
bar = 3
def baz; bar end
new.baz # => error
end
你可以把一个常数,并用它实例和类方法:
class Foo
Bar = 3
def local_bar(param = Bar)
param
end
end
p Foo.new.local_bar
#=> 3
这是一个局部变量,就像任何其他局部变量。 –