Ruby:实例变量与局部变量

标签 ruby

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

最佳答案

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

相关文章:

ruby-on-rails - 如何跳过 has_secure_password 验证

ruby - Regexp.escape 不转义正斜杠?

ruby-on-rails - 使用 Factory_girl 建立测试中关联

ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test

ruby - 需要 gem 中可执行文件中的文件

ruby-on-rails - 如何根据表列安排任务?

ruby-on-rails - 如何解决 Marshal.dump "no marshal_dump is defined for class Proc"错误

ruby - 如何根据其拥有的字段使用 Mechanize 选择表单?

Ruby:查找最近修改的文件

ruby-on-rails - "Export"Ruby 中的 x509 证书