Ruby・Railsで集合を扱う【基本編】

Ruby

それぞれの集合に数字と文字列の例を記載します。

和集合 (Union)

|演算子を使います。

a = [1, 2, 3]
b = [3, 4, 5]
union = a | b
p union  # => [1, 2, 3, 4, 5]

a = ["apple", "banana", "cherry"]
b = ["banana", "cherry", "date"]
union = a | b
p union  # => ["apple", "banana", "cherry", "date"]

積集合 (Intersection)

&演算子を使います。

a = [1, 2, 3]
b = [3, 4, 5]
intersection = a & b
p intersection  # => [3]

a = ["apple", "banana", "cherry"]
b = ["banana", "cherry", "date"]
intersection = a & b
p intersection  # => ["banana", "cherry"]

差集合 (Difference)

-演算子を使います。

a = [1, 2, 3]
b = [3, 4, 5]
difference_ab = a - b
difference_ba = b - a
p difference_ab  # => [1, 2]
p difference_ba  # => [4, 5]

a = ["apple", "banana", "cherry"]
b = ["banana", "cherry", "date"]
difference_ab = a - b
difference_ba = b - a
p difference_ab  # => ["apple"]
p difference_ba  # => ["date"]

対称差 (Symmetric Difference)

対称差はRubyの配列に直接的なメソッドがないため、和集合と積集合を使って計算することができます。

a = [1, 2, 3]
b = [3, 4, 5]
symmetric_difference = (a | b) - (a & b)
p symmetric_difference  # => [1, 2, 4, 5]

a = ["apple", "banana", "cherry"]
b = ["banana", "cherry", "date"]
symmetric_difference = (a | b) - (a & b)
p symmetric_difference  # => ["apple", "date"]

タイトルとURLをコピーしました