Orie - 2 years ago 109
Ruby Question

# Calculator that takes an operator as user input

I'm trying to create a calculator that takes user input. I want this input to include not just the numbers, but the operator as well (

`+`
,
`-`
,
`*`
,
`/`
). I created a method that works with a given parameter. Here is my code:

``````def calculator(x, y, z)
if y == '+'
ans = x + z
elsif y == '-'
ans = x - z
elsif y == '*'
ans = x * z
elsif y == '/'
ans = x / z
end
p ans
end

calculator(3, '+', 5)
calculator(4, '-', 2)
calculator(3, '*', 10)
calculator(21, '/', 7)

user_calc = gets.chomp

user_calc.chars
user_calc[0].to_i
user_calc[4].to_i
calculator(user_calc[0], user_calc[2], user_calc[4])
``````

The program assumes index
`0`
to be the first integer, index
`2`
the operator, and index
`4`
the second integer.

When I input
`3 + 5`
, the output is
`35`
`8`
. Any other operation (
`-`
,
`*`
,
`/`
) returns
`nil`
. When I try to use user input, I run into an error. I think it treats everything in the array as a string. The given parameters work as intended. But I cannot quite nail down the user input.

I'm wondering how I would go about fixing this.

`user_calc[0].to_i` returns a number as its result; it doesn't turn `user_calc[0]` into one. So

``````calculator(user_calc[0], user_calc[2], user_calc[4])
``````

is doing

``````calculator("3", "+", "5")
``````

and `"3" + "5"` is `"35"`.

The correct way would be to write

``````calculator(user_calc[0].to_i, user_calc[2], user_calc[4].to_i)
``````

or

``````arg1 = user_calc[0].to_i
arg2 = user_calc[4].to_i
calculator(arg1, user_calc[2], arg2)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download