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または、 2 回入力する必要がない方法で。これは怠惰からであり、知りたいです。

4

6 に答える 6

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

aただし、これは回避したいコードよりも大幅に遅くなります。少なくとも、bcが基本データである限りは。私の測定値は 3 倍でした。これはおそらく追加のArrayオブジェクト作成によるものです。したがって、ここでは DRY とパフォーマンスを比較検討する必要があるかもしれません。ただし、どちらのバリアントも時間がかからないため、通常は問題になりません。

于 2013-05-16T10:25:22.937 に答える
3

これが機能しない理由を本当に知っておく必要があります。

(a || c) == b

これは「a or c is equal b」という文を英訳したようなもので、意味が通じます。

ほとんどすべてのプログラミング言語で、(a || c)は式であり、その評価結果は と比較されbます。英語への翻訳は、「演算 "a または c" の結果は 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

これはどうですか?if [a,c].index(b) != nil;puts "b = a or b = c";end

于 2014-03-06T00:07:48.000 に答える