user3059932
user3059932

Reputation: 37

Variables in if/else statement won't work

I'm creating an interactive story, not a game. The options don't work in the if/else; here is the code.

puts "Choose (1)yes or (2)no"
choice = gets.chomp
if #{choice}==1
  puts "you chose yes"
elsif #{choice}==2
  puts "you chose no"
else
  puts "Invalid Choice"

I tried leaving it intro, but that just calls the else statement, and with this setup, the tic tac toe guy in front of the brackets, it always calls the first option. please help.

Upvotes: 1

Views: 159

Answers (1)

user229044
user229044

Reputation: 239240

if #{choice}==1 isn't how you test the value of variables. #{} is for string interpolation; you don't have to interpolate anything. Just use if choice == "1". Note that, because you're reading a string from the console, you need to compare against "1", not 1.

puts "Choose (1)yes or (2)no"

choice = gets.chomp

if choice == "1"
  puts "you chose yes"
elsif choice == "2"
  puts "you chose no"
else
  puts "Invalid Choice"
end

Upvotes: 5

Related Questions