我现在正在学习 Ruby,我很困惑为什么我可以在没有 @ 符号的情况下引用实例变量,这也会使它成为局部变量。当然,下面的代码不应该像它那样工作:
class Test
attr_accessor :variable
def something
variable
end
def something2
@variable
end
def something3
self.variable
end
end
y = Test.new
y.variable = 10
puts y.something # => 10
puts y.something2 # => 10
puts y.something3 # => 10
我本以为 y.something
会返回 nil。为什么局部变量和实例变量指向同一个位置?我原以为 @variable
和 variable
是两个离散变量。
最佳答案
在您发布的代码中,variable
是不是 局部变量。它是对名为 variable
的实例方法的方法调用,它由以下内容定义:
attr_accessor :variable
这是以下方法定义的简写:
def variable
@variable
end
def variable=(value)
@variable = value
end
请注意,Ruby 不需要括号 ()
来调用方法,因此区分局部变量和方法并不总是那么容易。
将您的代码与:
class Test
attr_accessor :foo
def example1
foo = nil # 'foo' is now a local variable
foo
end
def example2
foo # 'foo' is a method call
end
end
x = Test.new
x.foo = 10
x.example1 # => nil
x.example2 # => 10
关于Ruby:实例变量与局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6122481/