我有以下代码:
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
我需要它获取用户输入的 num1
和 num2
变量并验证它们是数字,如果不是则返回一条消息。
我想使用正则表达式,但我不知道是应该为此创建一个方法还是将其包装在一个循环中。
最佳答案
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/