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?
Asked
Active
Viewed 1,214 times
3 Answers
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
2
Use send
.
3.send("+", 5) # => 8

sawa
- 165,429
- 45
- 277
- 381
-
why send and not public_send? what diff? – Darlan Dieterich Oct 09 '20 at 19:21
1
Ruby has messages instead of methods, so you can do this:
1.send('+', 2) # => 3

Hauleth
- 22,873
- 4
- 61
- 112