2016-01-11 66 views
-1

所以我只是在製作一個隨機代碼生成器,並且我添加了一個循環,以便您可以再次運行而不再運行它。但顯然,當我在最後輸入yes時,它會再次出現,但是當我輸入no時,仍然會再次出現。輸入字符串時循環不會中斷

這裏是我的代碼:

loop do 
puts "Hello. I am a random code generator. PLease type in how many digits you want" 
b = gets.chomp.to_i 
a = rand *10**b 
puts "Your random code is #{a.to_i}" 
puts "Would you like to go again?" 
x = gets 
    if x == 'no' 
break 
end 
end 
+1

提示:你使用'chomp'一次,'gets'兩次。 – meagar

+0

當您第二次通過'gets'輸入字符串時,您將追加換行符。因此,您需要再次撥打chomp才能將其刪除。 – fmi11

回答

1
loop do 
    puts "Hello. I am a random code generator. PLease type in how many digits you want" 
b = gets.chomp.to_i 
a = rand *10**b 
    puts "Your random code is #{a.to_i}" 
    puts "Would you like to go again?" 
x = gets.chomp 
if x == 'no' 
    break 
    end 
end