Can I dynamically call a math operator in Ruby?

Is there something similar in ruby?

send(+, 1, 2) 

I want this piece of code to look less redundant

 if op == "+" return arg1 + arg2 elsif op == "-" return arg1 - arg2 elsif op == "*" return arg1 * arg2 elsif op == "/" return arg1 / arg2 
+4
source share
2 answers

Yup, just use send (or better yet, public_send ) like that

 arg1.public_send(op, arg2) 

This works because most of the operators in Ruby (including + , - , * , / , and much more ) just call methods. So, 1 + 2 coincides with 1.+(2) .

You can also use the whitelist op if its user input, for example. %w[+ - * /].include?(op) , because otherwise the user will be able to call arbitrary methods (which is a potential security vulnerability).

+12
source

As another option, if your operator and operands are in string format, say using the gets method, you can also use eval :

For instance:

a = '1'; b = '2'; o = '+'

eval a+o+b

becomes

eval '1+2'

which returns 3

0
source

Source: https://habr.com/ru/post/1385422/


All Articles