Search code examples
rubyoperation

Ruby Get a operator and make it work as one


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

Solution

  • 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.