You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby开发简易计算器:如何判断输入的字符/符号是否为数字

实现方案

你原有代码的核心问题是直接对输入调用to_i会将非数字内容强制转为0,无法区分合法输入0和非法字符,可通过正则匹配加if-else判断实现输入校验,完整可运行代码如下:

# 提取公共方法循环获取合法整数
def get_valid_number(prompt)
  loop do
    print prompt
    input_str = gets.chomp
    # if-else核心判断逻辑:匹配整数格式(支持负整数,单独负号、字母均不匹配)
    if input_str.match?(/^-?\d+$/)
      return input_str.to_i
    else
      puts "Error: Enter correct number"
    end
  end
end

# 获取合法运算符
def get_valid_operator(prompt)
  loop do
    print prompt
    op = gets.chomp
    if %w[+ - * /].include?(op)
      return op
    else
      puts "Error: Enter correct operator (+-*/)"
    end
  end
end

# 主流程
num1 = get_valid_number("Enter first number: ")
num2 = get_valid_number("Enter second number: ")
operator = get_valid_operator("Choose operator (+-*/): ")

# 计算输出结果
result = case operator
when '+' then num1 + num2
when '-' then num1 - num2
when '*' then num1 * num2
when '/' then num1.to_f / num2
end

operation_name = case operator
when '+' then 'sum'
when '-' then 'difference'
when '*' then 'product'
when '/' then 'quotient'
end
puts "The #{operation_name} is: #{result}"

如果需要支持小数输入,只需要将判断整数的正则改为/^-?\d+(\.\d+)?$/,同时将返回值的to_i改为to_f即可。

内容的提问来源于stack exchange,提问作者jan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:54:04