1

I have a program that takes a string as a parameter, but the user also enters in what operator they want to perform. They enter in the operator as a string and I need to convert it to an actual operator that would work. What is the best way to convert "+" to + so that it can be used as an operator?

xeroshogun
  • 1,062
  • 1
  • 18
  • 31

3 Answers3

4

use public_send. send is more dangerous, because it lets you also call private methods.

3.public_send("+", 5) # => 8
3.public_send("system", "rm *.txt") # => NoMethodError: private method `system' called for 3:Fixnum

You can check if the user has given a valid method by calling respond_to?

3.respond_to?("+")      # => true
3.respond_to?("sinus")  # => false

Better is that you white list the allowed operators

allowed = ["+", "*", "-", "/", "^", "modulo",]
if allowed.include? given_operator
  num.public_send(given_operator, arg1)
else
  puts "invalid operator given"
enU
zetetic
  • 47,184
  • 10
  • 111
  • 119
Meier
  • 3,858
  • 1
  • 17
  • 46
2

Use send.

3.send("+", 5) # => 8
sawa
  • 165,429
  • 45
  • 277
  • 381
1

Ruby has messages instead of methods, so you can do this:

1.send('+', 2) # => 3
Hauleth
  • 22,873
  • 4
  • 61
  • 112