可以在Ruby中缩短“if(a == b || c == b)”语句
发布时间:2020-12-16 19:34:04 所属栏目:百科 来源:网络整理
导读:我在 Ruby中有一段代码如下: def check if a == b || c == b # execute some code # b = the same variable endend 这可以写得像 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 thoug
我在
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和c是基本数据.我的测量结果显示因子为3.这可能是由于创建了额外的Array对象.所以你可能不得不在这里权衡DRY与性能.通常情况下,这并不重要,因为两种变体都不会花费很长时间. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |