这应该重构为更干吗?

时间:2017-10-29 13:10:03

标签: ruby refactoring conditional dry

我正在通过Chris Pine的第6章Deaf Grandman挑战。它看起来很可读,但我想知道这是否违反了DRY原则。如果是这样,我该如何重构呢?

puts "WHAT DID YOU SAY??"
said = gets.chomp
x = 0
bye_counter = 0

while bye_counter < 3
  if said != said.upcase
    puts "HUH?! SPEAK UP, SONNY!"
    said = gets.chomp
    bye_counter = 0

  elsif said == said.upcase && said != "BYE"
    puts "NO, NOT SINCE " + rand(1930..1950).to_s + "!"
    bye_counter  = 0
    said = gets.chomp

  elsif said == "BYE"
    puts "HUH??"
    bye_counter += 1
    break if bye_counter == 3
    said = gets.chomp
  end
end
puts "OH.. OK!"

1 个答案:

答案 0 :(得分:2)

我的解决方案:

message = "WHAT DID YOU SAY??"
bye_counter = 0
puts message

while bye_counter < 3
  said = gets.chomp
  if said == "BYE"
    message = "HUH??"
    bye_counter += 1
  else 
    if said == said.upcase
        message = "NO, NOT SINCE " + rand(1930..1950).to_s + "!"
    else
        message = "HUH?! SPEAK UP, SONNY!"
    end
    bye_counter  = 0
  end
  break if bye_counter == 3
  puts message
end
puts "OH.. OK!"