获取一个字符串,如果它与正则表达式匹配则返回它

时间:2015-12-01 12:12:52

标签: ruby loops

无法找到更好的方法来编写以下内容:

def get_name
  print "Please enter your name: "
  name = ""
  loop do
    break if (name = gets.chomp).match(/^[[:alpha:]]+$/)
    print "Please enter your name again (must be one or more letters): "
  end
  name
end

如何以更好的方式编写这个ruby方法?

4 个答案:

答案 0 :(得分:4)

您的代码问题在于它正在尝试同时执行两个完全不同的功能:验证格式和处理用户输入。最好将两者分开。你怎么看待这个?

def format_ok?(name)
  name =~ /\A[[:alpha:]]+\z/
end

def get_name
  print "Please enter your name: "
  loop do
    name = gets.chomp
    return name if format_ok?(name)
    print "Please enter your name again (must be one or more letters): "
  end
end

答案 1 :(得分:2)

这是另一种写作方式:

def get_name
  print "Please enter your name: "
  until gets =~ /^[[:alpha:]]+$/
    print "Please enter your name again (must be one or more letters): "
  end
  $_.chomp
end

它从标准输入读取一行,直到它与正则表达式匹配,否则打印错误消息。成功后,它会返回选择的行(gets分配给$_)。

答案 2 :(得分:1)

只是提供一个变体:

def prompt_name(p)
    puts p
    gets.chomp.strip
end

def get_name
    name = ''
    name = prompt_name("Please enter your name #{name.empty? ? '' : 'again '}:") while name !~ /\A[[:alpha:]]+\z/
    name
end

答案 3 :(得分:0)

怎么样?

def get_name
  print "Please enter your name: "
  name = gets.chomp
  until name  =~ /[[:alpha:]]/
    print "Please enter your name again (must be one or more letters): "
    name = gets.chomp
  end
    puts "your name is #{name}"
end

get_name

 > get_name
# Please enter your name: 3212
# Please enter your name again (must be one or more letters): 12Gagan
# your name is 12Gagan

Demo