我有以下代码:
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
个变量并验证它们是数字并返回消息(如果它们不是)。
我想使用正则表达式,但我不知道是否应该为此创建一个方法,或者只是将它包装在一个循环中。
答案 0 :(得分:4)
当给定字符串不是有效数字时,Integer
方法将引发异常,而to_i
将无声地失败(我认为这不是所希望的行为):
begin
num = Integer gets.chomp
rescue ArgumentError
say "Invalid number!"
end
如果你想要一个正则表达式解决方案,这也可行(虽然我推荐上面的方法):
num = gets.chomp
unless num =~ /^\d+$/
say "Invalid number!"
end
答案 1 :(得分:0)
您经常会看到每个部分都写成这样的内容:
ERR_MSG = "You must enter a non-negative integer"
def enter_non_negative_integer(instruction, error_msg)
loop do
puts instruction
str = gets.strip
return str.to_i if str =~ /^\d+$/
puts error_msg
end
end
x1 = enter_non_negative_integer("What's the first number?", ERR_MSG)
x2 = enter_non_negative_integer("What's the second number?", ERR_MSG)
这是可能的对话:
What's the first number?
: cat
You must enter a non-negative integer
What's the first number?
: 4cat
You must enter a non-negative integer
What's the first number?
: 22
#=> 22
What's the second number?
: 51
#=> 51
x1 #=> 22
x2 #=> 51