简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM