2014-11-10 4 views
1

У меня есть следующий код:Нужна помощь проверки, если пользовательский ввод номер

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

При подаче кода, снизить его до минимума, необходимого для репликации проблемы. Другими словами, было бы достаточно, например, 'num1 = gets.chomp', а также еще одна строка, показывающая, как вы пытались проверить числовое значение. –

ответ

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 
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 
Смежные вопросы