Ruby:实例变量与局部变量

时间:2011-05-25 09:48:31

标签: ruby

我现在正在学习Ruby,我很困惑为什么我可以在不使用@sigil的情况下引用实例变量,这也会使它成为局部变量。当然,以下代码不应该像以下那样工作:

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会返回零。为什么局部变量和实例变量指向同一位置?我原以为@variablevariable是两个离散变量。

1 个答案:

答案 0 :(得分:19)

在您发布的代码中,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