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

时间:2013-05-16 10:21:16

标签: ruby

我在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的方式。这是懒惰,我想知道。

6 个答案:

答案 0 :(得分:20)

if [a, c].include? b
  # code
end

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

答案 1 :(得分: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

随意打开最近的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

现在运行

case a
when b, c then true
else false end

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

答案 2 :(得分:3)

你应该知道为什么这不起作用:

(a || c) == b

这似乎是句子“a或c等于b”的翻译,这在英语中是有意义的。

在几乎所有编程语言中,(a || c)都是一个表达式,其评估结果将与b进行比较。翻译成英语是“操作的结果”a或c“等于b”

答案 3 :(得分:0)

@ undur_gongor的回答是完全正确的。只是要添加,但是如果您正在使用数组,例如:

a = [1,2,3]
c = [4,5,6]

b = [5,6]

if [a, c].include? b
  # won't work if your desired result is true
end

你必须做类似的事情:

if [a,c].any?{ |i| (i&b).length == b.length }
  # assuming that you're always working with arrays
end

# otherwise ..
if [a,c].any?{ |i| ([i].flatten&[b].flatten).length == [b].flatten.length }
  # this'll handle objects other than arrays too.
end

答案 4 :(得分:-1)

这个怎么样? if [a,c] .index(b)!= nil; put“b = a or b = c”; end

答案 5 :(得分:-1)

Acolyte指出你可以使用b == (a||c),你只是向后使用它,但这只适用于左值,因为(a || c)总是a,假设a不是假的。

另一种选择是使用三元运算符。

a==b ? true : b==c

我不确定阵列方法引用的速度差异,但我认为这可能更快,因为它正在进行一两次比较而不需要处理数组。另外,我认为它与(a == b || b == c)完全相同,但它是一种风格替代品。