Это отделяет сложную логику от IO
def validation_message_for_word(word)
case
when (word.nil? or word.empty?) then "Nothing to input."
when word.include?(":") then 'Illegal character ":".'
else nil
end
end
word = nil # To ensure word doesn't get thrown away after the loop
loop do
print "Input word: "
word = gets.chomp
validation_message = validation_message_for_word(word)
break if validation_message.nil?
puts validation_message
end
Теперь, если вы хотите выполнить его модульное тестирование, вы можете присвоить validation_message_for_word
различные строки и проверить возвращаемое значение.
Если вам нужна интернационализация, вы можете сделать
def validation_type_for_word(word)
case
when (word.nil? or word.empty?) then :no_input
when word.include?(":") then :illegal_character
else nil
end
end
def validation_message(language, validation_type)
{:en => {:no_input => "No input", :illegal_character => 'Illegal character ":"'},
:lolcat => {:no_input => "Invizibl input", :illegal_character => 'Character ":" DO NOT LIEK'}}.fetch(language).fetch(validation_type)
end
word = nil # To ensure word doesn't get thrown away after the loop
loop do
print "Input word: "
word = gets.chomp
validation_type = validation_type_for_word(word)
break if validation_type.nil?
puts validation_message(:lolcat, validation_type)
end