我正在尝试将正整数分配给项目列表。正整数是用户输入。我正在使用Ruby 1.9.3-p327
如果用户输入负数(任何< 0)或0本身或小数或任何字母数字数据,我会在while循环中放置一个条件,请求用户再次输入该数字。
我当前的代码在循环中是: -
input_data = gets.chomp
while (input_data.to_i <= 0 || input_data.include?(".") || /^[-+]?[0-9]+$/.match(input_data).nil?)
puts "input_data can't be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate input_data as a +ve integer "
input_data = gets.chomp
end
我确信会有更优化的方法来做到这一点。我想它可能正在使用组合的正则表达式检查。我是Ruby中正则表达式的新手。有什么建议吗?
由于
答案 0 :(得分:1)
使用正则表达式:
input_data = gets.chomp
while input_data !~ /^[1-9]\d*$/
puts "input_data can't be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate input_data as a +ve "
input_data = gets.chomp
end