if statement - New to Ruby, trouble with if and gets function -


puts "the road splits, go left or right?"  choice = gets if choice == 'right'   puts "you walk right" elsif choice == 'left'   puts "you walk left" else   puts "not valid choice"   puts choice   puts choice.class end 

no matter type returns false. tried same thing changing 'right' , 'left' 1 , 2, , worked.

the string returned gets include "\n" @ end unless you're end of file.

use string#chomp (choice = gets.chomp) rid of it.

if you're not sure what's going on, use p print out debugging info, e.g.: p choice unlike puts, returns printed expression can chain , runs .inspect on before printing it, allowing see representation. puts little bit of magic -- namely doesn't add newline if argument ends one. trick puts might have made finding source of problem little bit more difficult.


Comments

Popular posts from this blog

android - How to save instance state of selected radiobutton on menu -

python 3 IndexError: list index out of range -

IF statement in MySQL trigger -