Hubert Jakubiak Hubert Jakubiak - 1 month ago 8
Ruby Question

Why this instance variable is not incrementing?

This short code is working when I'm using class variable

@@points
instead of
@points
. I wonder why it's happening like this? Someone can explain me? It looks like
@points
is always
nil
.

class Game

@points = 0

def start

until @points == 10
puts "Guess number between 0 and 10:"
num = gets.chomp.to_i
break if @points == 0
guess_number(num)
puts "Your score is: #{@points}"

end

end

def guess_number(num)
@points += 1 if num == rand(0..10)
end

end

game = Game.new
game.start

Answer

Because @points is a class instance variable, and you do not have access to it from within the instance method's scope.

code is working when I'm using class variable @@points instead of @points

It is working, because you do have access to class variable from within a scope of an instance methods.

It looks like @points is always nil

It is always nil, because you never defined an instance variable @points, but, as said, class instance variable.

So these three things are different (you could read up something about Ruby scoping - do not mix with AR scopes):

  • class variable
  • class instance variable
  • instance variable

To solve it there are many ways, but if you want to keep it on the instance level, wrap @points into a method:

def points
  @points ||= 0
end

And then use it as points - now it'll work as you are expecting.

Comments