而Ruby中的循环Pt.2

时间:2015-03-16 04:32:49

标签: ruby

我希望程序只在我连续3次<{1}} 连续后退出。我的节目截至目前,当我说'BYE' 3次时退出,但我不知道如何连续播出。我完全失去了。

'BYE'

1 个答案:

答案 0 :(得分:0)

所以解决方法是,如果你得到的不是再见 - 再次将计数器重置为0

what_said = 'Hi!'
bye_count = 0

while (bye_count < 3)
  what_said = gets.chomp
  if (what_said == 'BYE')
    if (bye_count < 2)
      bye_count += 1
      puts 'WHAT DID YOU SAY??'
    else
      bye_count += 1
      puts 'FINE! LEAVE YOUR POOR GRANDMA TO DIE.'
    end
  else
    # didn't get bye, so reset counter to 0 again
    bye_count = 0

    if (what_said == what_said.upcase)
      puts 'NO, NOT SINCE ' + rand(1930...1951).to_s + '!'
    else
      puts 'HUH!? SPEAK UP, SONNY!'
    end
  end
end