ruby - 需要帮助验证用户输入是否为数字

标签 ruby regex

我有以下代码:

def say(msg)
  puts "=> #{msg}"
end

def do_math(num1, num2, operation)
  case operation
    when '+'
      num1.to_i + num2.to_i
    when '-'
      num1.to_i - num2.to_i
    when '*'
      num1.to_i * num2.to_i
    when '/'
      num1.to_f / num2.to_f
    end
end

say "Welcome to my calculator!"

run_calculator = 'yes'

while run_calculator == 'yes'
  say "What's the first number?"

  num1 = gets.chomp

  say "What's the second number?"

  num2 = gets.chomp

  say "What would you like to do?"

  say "Enter '+' for Addition, '-' for Subtraction, '*' for Multiplication, or '/' for Division"

  operation = gets.chomp

  if num2.to_f == 0 && operation == '/'
    say "You cannot devide by 0, please enter another value!"
    num2 = gets.chomp
  else
    result = do_math(num1, num2, operation)
  end

  say "#{num1} #{operation} #{num2} = #{result}"

  say "Would you like to do another calculation? Yes / No?"
  run_calculator = gets.chomp

  if run_calculator.downcase == 'no'
    say "Thanks for using my calculator!"
  elsif run_calculator.downcase == 'yes'
    run_calculator = 'yes'
  else
    until run_calculator.downcase == 'yes' || run_calculator.downcase == 'no'
      say "Please enter yes or no!"
      run_calculator = gets.chomp
    end
  end
end 

我需要它获取用户输入的 num1num2 变量并验证它们是数字,如果不是则返回一条消息。

我想使用正则表达式,但我不知道是应该为此创建一个方法还是将其包装在一个循环中。

最佳答案

Integer当给定的字符串不是有效数字时,方法将引发异常,而 to_i将无声地失败(我认为这不是期望的行为):

begin
  num = Integer gets.chomp
rescue ArgumentError
  say "Invalid number!"
end

如果你想要一个正则表达式的解决方案,这也可以(尽管我推荐上面的方法):

num = gets.chomp
unless num =~ /^\d+$/
  say "Invalid number!"
end

关于ruby - 需要帮助验证用户输入是否为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26852597/

相关文章:

ruby-on-rails - 为什么我的测试没有通过?

regex - 用 N 个字符替换行首的 N 个空格

ruby - 如何生成六种随机的十六进制颜色并将它们放入 Ruby 数组中?

正则表达式匹配以特殊字符开头的单词边界

javascript - 将 URL 或完全限定域名替换为链接

excel - 在 Excel 函数上提取大写单词

MySQL:日志显示记录已存在

ruby-on-rails - 如何使用 `params[:user][:delete]` 向 Controller 发送类似 `check_box_tag` 的参数值?

python - 正则表达式查找包含 "-"的单词

python - 如何忽略 python 中正则表达式拆分中的组?