0

I have

board_a1 = " [ ] "
board_a2 = " [ ] "
board_a3 = " [ ] "

etc. I prompt the user, and get input:

puts "Choose your square"
user_input = gets.chomp.downcase

If the user types in "a2", I need to reassign board_a2:

board_a2 = " [X] "

How would I match the user input to reassign the proper board square? I thought I could concatenate the pieces like so:

board_assignment = "board_#{user_input}"

Then use

board_assignment = " [X] "

But board_assignment != board_a2. It's a new variable. I need to reassign the proper variable based on the user input right after the user types it in. Is there some special syntax to concatenate strings that can then represent the existing variable? What do you call this situation, and how would I go about getting my dynamic variable set?

1 Answer 1

2

You should use a single variable, which contains a hash, mapping the space's name to its current state:

board = {
  "a1" => " [ ] ",
  "a2" => " [ ] ",
  "a3" => " [ ] "
}

The rest becomes pretty self-explanatory. When the user enters "a2", modify the value at board["a2"].

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

3 Comments

Thanks, but I forgot to mention, I'm using a1 = "a1" as part of a different method for the game logic. The board_a1 is purely for display. But... hmmm... I think I can still use the board{} hash. Let me fiddle. Thanks!
I'm having a problem. I need to do board[#{user_choice}] = user_choice but ruby doesn't like that. Any ideas?
It's just board[user_choice] = user_choice, #{} is for string interpolation between double quotes. You should probably read a tutorial on Ruby, as this is pretty basic syntax. Please stop adding comments to this answer; if you have any other questions, ask another question.

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.