귀하의 while (count != 3)
은 Rubishque 솔루션을 작성하는 데 저항 할 수 없을 정도로 자바 (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'
가 실행 :
$ 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