0

This is a part of my code for a Naughts and Crosses (tic-tac-toe) game.

positions = [" ", " ", " ", " ", " ", " ", " ", " ", " "]

# Returns .. 1 = Square already owned, 2 = Blank square, 0 = Enemy square
def check_square(side, square)
  if positions[square] == side
    state = 1
  elsif positions[square] == B
    state = 2
  else
    state = 0
  end
  return state
end

When I run the program I get the error:

in `check_square': undefined local variable or method `positions' for main:Object (NameError)

However it is literally defined right above it. I have ran the snippet of code in its own .rb and it works fine so I don't see why it doesn't work. I must assume it has to do with the scope of positions but, for me at least (beginner programmer), I don't see why it doesn't work here but does in its own program.

Any help is gladly appreciated.

1 Answer 1

1

A local variable's scope cannot cross a method definition. positions that is assigned outside of the method definition is not visible from within the method definition.

To make it visible, you can make it an instance variable, class variable, global variable, or constant, for example. Or, you can pass it as an argument to the method.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, I have set it to a global variable and it now seems to work!
However, global variable is not recommended in object oriented programming.
what would you recommend I use instead?
instance variable or constant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.