我有一段 Ruby 代码,如下所示:
def check
if a == b || c == b
# execute some code
# b = the same variable
end
end
这可以写成这样
def check
if a || c == b
# this doesn't do the trick
end
if (a || c) == b
# this also doesn't do the magic as I thought it would
end
end
或者以一种我不需要打字的方式b
两次。这是出于懒惰,我想知道。
if [a, c].include? b
# code
end
然而,这比您想要避免的代码要慢得多——至少只要a
, b
and c
是基础数据。我的测量结果显示系数为 3。这可能是由于额外的Array
对象创建。因此,您可能必须在这里权衡 DRY 与性能。不过,通常情况下这并不重要,因为这两种变体都不需要很长时间。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)