开发者

Ruby: Instance variables vs local variables

I'm learning Ruby right now, and I'm confused as to why I can refer to an instance variable without the @ sigil, which would make it a local variable too. Surely the following code shouldn't work as it does:

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

I'd have expected y.something to return nil. Why do local variables and instance variables point to the same location? I'd have expected @variable and variable to have been two discrete variables.


In the code you posted, variable is not a local variable. It is a method call to the instance method named variable, which was defined by:

attr_accessor :variable

This is a shorthand for the following method definitions:

def variable
  @variable
end

def variable=(value)
  @variable = value
end

Note that Ruby does not require parentheses () for a method call, so distinguishing between a local variable and a method is not always easy.

Compare your code with:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜