Hubert Jakubiak Hubert Jakubiak - 1 year ago 82
Ruby Question

Why this instance variable is not incrementing?

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

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

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
puts "Your score is: #{@points}"



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


game =

Answer Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download