xeroshogun
xeroshogun

Reputation: 1092

Ruby- How to covert a string into an operator

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?

Upvotes: 1

Views: 1310

Answers (3)

Meier
Meier

Reputation: 3880

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

Upvotes: 4

Hauleth
Hauleth

Reputation: 23556

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

1.send('+', 2) # => 3

Upvotes: 1

sawa
sawa

Reputation: 168071

Use send.

3.send("+", 5) # => 8

Upvotes: 2

Related Questions