1

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
  • 1
    You can find a similar example in this questions: https://stackoverflow.com/questions/31331287/no-method-error-ruby-calculator or https://stackoverflow.com/questions/38649405/making-ruby-calculator-run-continuously or https://stackoverflow.com/questions/25572500/why-isnt-this-ruby-calculator-working-as-intended – knut Nov 17 '19 at 21:25
  • Thanks so much @knut, but is there a way to convert "+" into a operator, but using gets? – Ernani Rocha Nov 17 '19 at 22:32

3 Answers3

3

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.

Masa Sakano
  • 1,921
  • 20
  • 32
1

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.

knut
  • 27,320
  • 6
  • 84
  • 112
  • `num1 = 2 num2 = 3 op = + puts (num1 op.public_send num2)` Thanks so much for taking the time. Why my code above won´t work? – Ernani Rocha Nov 18 '19 at 18:38
  • Why should it? I guess there are some newlines missing. You can replace it with a semicolon. I guess you look for `num1 = 2 ; num2 = 3 ; op = '+' ; puts num1.public_send(op, num2)` Error 1: plus must be a string. Error 2: `public_send`is a method of Integer (here num1). - Bus this is a new question. – knut Nov 18 '19 at 19:17
0

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.

tdy
  • 36,675
  • 19
  • 86
  • 83
pablito
  • 21
  • 1
  • 5