我可以在 Ruby 中动态调用数学运算符吗? [英] Can I dynamically call a math operator in Ruby?
本文介绍了我可以在 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
推荐答案
是的,只需使用 <代码>发送(或者,更好的是,public_send
) 像这样:
Yup, simply use send
(or, better yet, public_send
) like so:
arg1.public_send(op, arg2)
这是因为 Ruby 中的大多数运算符(包括 +
、-
、*
、/
、1 + 2
和 1.+(2)
是一样的.
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屋!
查看全文