あなたのwhile (count != 3)
はRubishqueの解決策を書くのに抵抗することができないほどJavaに似ています(Rubyの括弧は不要です)。もっと短くはありませんが、DRYは、Rubyプログラムで見られる可能性の高いコードが多く、Rubyで同じことをする方法は常にたくさんあります。
class Strange
def initialize(wanted)
@answer = true
@count = 0
@wanted = wanted # desired number of correct consecutive answers
end
# Increment @count if true, else reset to zero.
def answer(boolean)
@answer = boolean
if boolean
then # then is optional, but I like it
@count = @count + 1
else
@count = 0
end
end
# Write a message.
def message(number)
puts case number
when 1 then 'HUH?! SPEAK UP, SONNY!'
when 2 then "NO, NOT SINCE #{rand(1930..1950)} !"
else 'WHAT ?'
end
end
def prompt
print @answer ? 'Talk please > ' : 'Wrong answer, retry > '
@ask = gets.chomp
end
# Recursively loop until the number of correct consecutive answers
# corresponds to the desired number.
def run
prompt
case
when @ask == 'BYE'
message 1
answer(true)
when @ask != @ask.upcase
message 1
answer(false)
else
message 2
answer(false)
end
run unless @count == @wanted # recursive loop
end
end # class Strange
Strange.new(3).run
puts 'Goodbye for now'
実行:
ループの先頭で一度だけ
gets
を置く
$ ruby -w t.rb
Talk please > xyz
HUH?! SPEAK UP, SONNY!
Wrong answer, retry > XYZ
NO, NOT SINCE 1935 !
Wrong answer, retry > BYE
HUH?! SPEAK UP, SONNY!
Talk please > what ?
HUH?! SPEAK UP, SONNY!
Wrong answer, retry > BYE
HUH?! SPEAK UP, SONNY!
Talk please > BYE
HUH?! SPEAK UP, SONNY!
Talk please > BYE
HUH?! SPEAK UP, SONNY!
Goodbye for now
あなたは0ということを理解して、 1,2,3は4回c orrect? – engineersmnky