Why are these methods not solved?

Given this code:

class Something
  attr_accessor :my_variable

  def initialize
    @my_variable = 0
  end

  def foo
    my_variable = my_variable + 3
  end
end

s = Something.new
s.foo

I get this error:

test.rb:9:in `foo': undefined method `+' for nil:NilClass (NoMethodError)
    from test.rb:14:in `<main>'

If it attr_accessorcreates a method called my_variable(and .. =), why foocan't it find the method? It works if I change it to self.my_variable, but why? Is the selfdefault receiver?

+5
source share
4 answers

You do not call the method there, you are actually referring to the same variable that you are in the process of defining! This worked out a bit in Ruby.

What would be better if you referenced and set the instance variable instead:

@my_variable = @my_variable + 3

Or shorter:

@my_variable += 3

Or you can call the setter method as you found (and Jits point ):

self.my_variable += 3

my_variable=, attr_accessor, . , my_variable=, - , , :

def my_variable=(value)
  # do something here
  @my_variable = value
end

BONUS

, :

my_variable = my_variable() + 3

" Ruby", , , .

+7
my_variable = my_variable + 3

... , .

, self - .

+5

my_variable foo, my_variable, my_variable=.

, self, .

See also this question: Why do we need ruby ​​setters. classroom qualifications?

+3
source

I think that in this case the scope of the variable is only inside the function, unless you add it with self.in @.

+2
source

All Articles