2016-09-23 50 views
2

我不知道爲什麼,即使我鍵入「Y」的條件總是假條件輸入值總是返回false(RUBY)

puts "Would you like to continue [y/n]" 
confirm = gets 
puts confirm == "y" # why this is not true even I type "y"  

if confirm == "y" 
    puts "Input is y" 
end 

回答

1

嘗試使用confirm = gets.chomp原因gets設置你到底

\n進入
> a = gets 
> y 
=> "y\n" 
+0

驚人消除任何不必要的字符,它解決它。謝謝,我會在9分鐘後回答它 – Beginner

1

請試試此代碼。

puts "Would you like to continue [y/n]" 
confirm = gets 
puts "|#{confirm}|" # y\n 
puts confirm.strip == "y" # gives you true 
puts confirm == "y" # gives you false 

if confirm == "y" 
    puts "Input is y" 
end 

你可以使用gets.stripgets.chompgets