是否应该将其重构为更 DRY?
Should this be refactored to be more DRY?
我正在完成 Chris Pine 的第 6 章聋人祖母挑战。它看起来非常可读,但我想知道这是否违反了 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!"
我的解决方案:
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!"
我正在完成 Chris Pine 的第 6 章聋人祖母挑战。它看起来非常可读,但我想知道这是否违反了 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!"
我的解决方案:
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!"