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).
source share