如何检查输入字符串?

时间:2011-06-20 07:03:38

标签: ruby loops input

这是我的代码:

loop do
  print "Input word: "
  word = gets.chomp
  if word.nil? or word.empty?
    puts "Nothing to input."
  else
    if word.index(":") != -1
      puts "Illegal character ':'"
    else
      break
    end
  end
end

是否有更优雅的方法来检查输入字符串?

4 个答案:

答案 0 :(得分:7)

这样的东西?

loop do
  print "Input word: "
  word = gets.chomp

  if word.empty?
    puts "No input."
  elsif word.include?(":")
    puts "Illegal character ':'"
  else
    break
  end
end

答案 1 :(得分:2)

这将复杂逻辑与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

答案 2 :(得分:0)

我个人更喜欢避免嵌套if / else:

loop do
    print "Input word: "
    word = gets.chomp
    if word.nil? or word.empty?
        puts "Nothing to input."
        #break, exit, nothing, or whatever ....
    end
    if word.index(":") != 0
        puts "Illegal character ':'"
    else
        break
    end
end

答案 3 :(得分:0)

取决于“优雅”对你意味着什么,但作为重构条件语句以便于读取提取方法的粉丝,我会看到类似的东西:

def has_valid_input(word)
  return true unless word.include?(":")
  puts "Illegal." 
  return false
end

def is_not_empty(word)
  return true unless word.empty?
  puts "empty"
  return false
end

loop do
  print "Input word: "
  word = gets.chomp
  break if is_not_empty(word) && has_valid_input(word)
end