Orie - 2 years ago 109

Ruby Question

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 (

`+`

`-`

`*`

`/`

`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)

puts "Please enter your calculation"

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`

`2`

`4`

When I input

`3 + 5`

`35`

`8`

`-`

`*`

`/`

`nil`

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

`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**