2つのRuby配列があり、それらに共通の値があるかどうかを確認する必要があります。一方の配列の各値をループして、もう一方の配列にinclude?()を含めることもできますが、もっと良い方法があると確信しています。それは何ですか?(配列は両方とも文字列を保持します。)
ありがとう。
a1 & a2
次に例を示します。
> a1 = [ 'foo', 'bar' ]
> a2 = [ 'bar', 'baz' ]
> a1 & a2
=> ["bar"]
> !(a1 & a2).empty? # Returns true if there are any elements in common
=> true
共通の値はありますか?交差演算子を使用できます:&
[ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
ただし、完全な交差を探している場合(重複がある場合)、問題はより複雑です。ここにはすでにスタックオーバーフローがあります。重複する要素を持つRuby配列の交差を返す方法は?(ダイス係数のバイグラムの問題)
または、 「real_intersection」を定義し、次のテストを検証するクイックスニペット
class ArrayIntersectionTests < Test::Unit::TestCase
def test_real_array_intersection
assert_equal [2], [2, 2, 2, 3, 7, 13, 49] & [2, 2, 2, 5, 11, 107]
assert_equal [2, 2, 2], [2, 2, 2, 3, 7, 13, 49].real_intersection([2, 2, 2, 5, 11, 107])
assert_equal ['a', 'c'], ['a', 'b', 'a', 'c'] & ['a', 'c', 'a', 'd']
assert_equal ['a', 'a', 'c'], ['a', 'b', 'a', 'c'].real_intersection(['a', 'c', 'a', 'd'])
end
end
交差点の使用は見栄えがしますが、非効率的です。私は「何か」を使いますか?最初の配列で(要素の1つが2番目の配列で見つかったときに反復が停止するように)。また、2番目の配列でSetを使用すると、メンバーシップチェックが高速になります。すなわち:
a = [:a, :b, :c, :d]
b = Set.new([:c, :d, :e, :f])
c = [:a, :b, :g, :h]
# Do a and b have at least a common value?
a.any? {|item| b.include? item}
# true
# Do c and b have at least a common value?
c.any? {|item| b.include? item}
#false
Ruby 3.1から、Array#intersect?
2つの配列に少なくとも1つの共通の要素があるかどうかをチェックする新しいメソッドがあります。
次に例を示します。
a = [1, 2, 3]
b = [3, 4, 5]
c = [7, 8, 9]
# 3 is the common element
a.intersect?(b)
# => true
# No common elements
a.intersect?(c)
# => false
また、Array#intersect?
中間配列の作成を回避し、共通の要素が見つかるとすぐにtrueを返し、Cで実装されるため、他の方法よりもはるかに高速になります。
出典:
これを試して
a1 = [ 'foo', 'bar' ]
a2 = [ 'bar', 'baz' ]
a1-a2 != a1
true