Skip to content

Instantly share code, notes, and snippets.

@yucao24hours
Last active December 20, 2015 04:49
Show Gist options
  • Save yucao24hours/6073280 to your computer and use it in GitHub Desktop.
Save yucao24hours/6073280 to your computer and use it in GitHub Desktop.
https://gist.github.com/yucato/6054328 でいただいたアドバイスをもとに書いたコード(「3回連続で'BYE'と叫ぶまで帰してくれないおばあちゃん」)その2 です。
puts 'Hello! May I help you?'
while true
word = gets.chomp
unless word == 'BYE'
# BYE以外を話しかけられた時はきちんと答える
if word.upcase == word
puts "Well, it hasn't happened since #{(1930..1951).to_a.sample} !"
else
puts 'Huh? Could you speak up, please??'
end
count = 0
else
# BYEと言われたときは聞こえないふりをして、何も答えない
count = count + 1
end
if count >= 3
# 3回連続でBYEと叫ばれたら、諦めてお別れする
break
end
end
puts 'Thanks. Come back anytime.'
@willnet
Copy link

willnet commented Jul 25, 2013

  • 最初の入力で 'BYE' を入力したら、14行目の count = count + 1 でエラーになってしまう気がします
  • unless ... else ... よりも、if ... else ... にしたほうが読みやすいかなと思います

@do-aki
Copy link

do-aki commented Jul 25, 2013

"3回連続でBYE" したことを while ループを抜ける条件にしてやれば終了条件が明確になるので

count = 0
begin
  ...
end while count < 3

と書くのもアリかと。

1930年から1950年のランダムな数字で毎回違う年を叫ぶようにしましょう。

なので、 (1930..1950) では?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment