[英](Ruby) Counting in Loops
你能幫我一下嗎?
我想以這樣的方式編寫Ruby代碼:當我說“再見!”一詞時 連續3次終止程序。
我的代碼如下
quotes = File.readlines('quotes.db')
puts = "What?"
print ">"
request = gets.chomp
while request != "BYE!"
puts quotes[rand(quotes.length)]
puts ">"
request = gets.chomp
end
我可以修改代碼以遵循我想要的規則嗎?
檢查這是否是您想要的。 並告訴我是否發生任何錯誤。 這可能是粗糙的代碼
quotes = File.readlines('quotes.db')
puts = "What?"
print ">"
counter = 0
request = gets.chomp
while counter < 3
counter += 1 if request.eqls?("BYE!")
puts quotes[rand(quotes.length)]
puts ">"
request = gets.chomp
end
我會做這樣的事情:
quotes = File.readlines('quotes.db')
counter = 0
puts 'What?'
loop do
print '>'
request = gets.chomp
if request == 'BYE!'
counter += 1
break if counter >= 3
else
counter = 0
end
puts quotes.sample
end
puts 'If you type bye 3 times, this program will terminate'
bye_counter = 0
loop do
input = gets.chomp
if input == 'bye'
bye_counter += 1
else
bye_counter = 0
end
break if bye_counter == 3
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.