Noob to the extreme here.
How can I make this operator work?
puts "Tell me a number"
num1 = gets
puts "Tell me an another number"
num2 = gets
puts "Tell me an operator"
op = gets
puts num1.to_i op num2.to_i
Noob to the extreme here.
How can I make this operator work?
puts "Tell me a number"
num1 = gets
puts "Tell me an another number"
num2 = gets
puts "Tell me an operator"
op = gets
puts num1.to_i op num2.to_i
In Ruby an operator is basically a method. Do this:
puts num1.to_i.public_send(op.chomp, num2.to_i)
With Object#public_send
, you can send a (public) method specified either with String or Symbol.
Note if your Ruby version is old, you may need replace public_send
with send
.
As you can see in other answers, you can use send
(or public_send
) to call a method.
There is one problem: gets
includes a newline (e.g. +\n
). The to_i
method can handle this. send
tries to find a methos with the newline (and will not find it). So you have to remove the newline from operator (using the strip
-method.
So the complete example:
puts "Tell me a number"
num1 = gets
puts "Tell me an another number"
num2 = gets
puts "Tell me an operator"
op = gets
puts num1.to_i.send( op.strip, num2.to_i)
I would recommend to convert the values immediate after reading it, it makes life easier later:
puts "Tell me a number"
num1 = gets.to_i
puts "Tell me an another number"
num2 = gets.to_i
puts "Tell me an operator"
op = gets.strip
puts num1.public_send( op, num2)
Be aware, there is no check for valid operators. When you enter
1
2
u
you get a undefined method 'u' for 1:Integer (NoMethodError)
-error.
The public_send
method shared already works perfectly well but here is an alternative way.
puts num1.to_i.method(op.chomp).(num2.to_i)
It basically does the exact same thing using Object#method
and Method#call
. I found this out thanks to this post and @ArapRakshit where I got the answers I needed.