在Ruby中可以缩短"if(a == b || c == b)"语句

Bik*_*ire 8 ruby

我在Ruby中有一段代码如下:

def check
  if a == b || c == b
  # execute some code
  # b = the same variable
  end
end
Run Code Online (Sandbox Code Playgroud)

这可以写得像

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
Run Code Online (Sandbox Code Playgroud)

或者以我不需要输入b两次的方式.这是出于懒惰,我想知道.

und*_*gor 20

if [a, c].include? b
  # code
end
Run Code Online (Sandbox Code Playgroud)

然而这是比代码显著慢要避免-至少只要a,b并且c是基本的数据.我的测量结果显示因子为3.这可能是由于Array创建了额外的对象.所以你可能不得不在这里权衡DRY和性能.但通常情况下,这并不重要,因为这两种变体都不需要很长时间.

  • 很好,但实际上它长了1个字符,我想这取决于变量名称.它对性能有影响吗? (2认同)
  • @zakinster::-)字符数不是问题的目标.重点是避免重复.而不是'b`可能会有更复杂的东西.或者,当用另一个变量交换"b"时,你不必在两个地方更改它(更少的错误). (2认同)

Bor*_*cky 6

虽然不完全相同a == b || a == c,但case语句提供了以下语法:

case a
when b, c then puts "It's b or c."
else puts "It's something else."
end
Run Code Online (Sandbox Code Playgroud)

随意打开最近的Ruby教科书,阅读有关case语句如何工作的内容.Spoiler:它通过调用#===比较对象的方法来工作:

a = 42
b, c = Object.new, Object.new
def b.=== other; puts "b#=== called" end
def c.=== other; puts "c#=== called" end
Run Code Online (Sandbox Code Playgroud)

现在跑

case a
when b, c then true
else false end
Run Code Online (Sandbox Code Playgroud)

这为您提供了很大的灵活性.它需要在后台工作,但在你做完后,在前台看起来像魔术.