8

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

4

6 回答 6

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

但是,这比您要避免的代码要慢得多——至少只要a,bc是基本数据。我的测量结果显示系数为 3。这可能是由于Array创建了额外的对象。因此,您可能必须在这里权衡 DRY 和性能。不过,通常这无关紧要,因为这两种变体都不需要很长时间。

于 2013-05-16T10:25:22.937 回答
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语句如何工作的信息。#===剧透:它通过在比较对象上调用方法来工作:

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

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

于 2013-05-16T12:35:42.710 回答
3

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

(a || c) == b

这似乎是对“a or c is equal b”句子的翻译,这在英语中是有意义的。

在几乎所有编程语言中,(a || c)是一个表达式,其评估结果将与b. 翻译成英文是"The result of the operation "a or c" is equal to b"

于 2013-05-16T12:35:15.323 回答
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
于 2013-05-16T11:15:08.590 回答
-1

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

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

a==b ? true : b==c

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

于 2014-03-06T00:35:11.077 回答
-1

那这个呢?if [a,c].index(b) != nil;puts "b = a or b = c";end

于 2014-03-06T00:07:48.000 回答