我可以在Ruby中动态调用数学运算符吗? [英] Can I dynamically call a math operator in Ruby?
本文介绍了我可以在Ruby中动态调用数学运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
红宝石里有这样的东西吗?
Is there something like this in ruby?
send(+, 1, 2)
我想让这段代码看起来不太多余
I want to make this piece of code seem less redundant
if op == "+"
return arg1 + arg2
elsif op == "-"
return arg1 - arg2
elsif op == "*"
return arg1 * arg2
elsif op == "/"
return arg1 / arg2
推荐答案
是的,只需使用 send
(或者更好的是, public_send
),就像这样:
Yup, simply use send
(or, better yet, public_send
) like so:
arg1.public_send(op, arg2)
之所以可以使用它,是因为Ruby中的大多数运算符(包括+
,-
,*
,/
,
This works because most operators in Ruby (including +
, -
, *
, /
, and more) simply call methods. So 1 + 2
is the same as 1.+(2)
.
如果op
是用户输入的内容,您可能还希望将其列入白名单. %w[+ - * /].include?(op)
,否则用户将能够调用任意方法(这是一个潜在的安全漏洞).
You may also want to whitelist op
if it’s user input, e.g. %w[+ - * /].include?(op)
, as otherwise the user will be able to call arbitrary methods (which is a potential security vulnerability).
这篇关于我可以在Ruby中动态调用数学运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文