0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

rubyの集合の引き算や足し算

Last updated at Posted at 2025-09-30

rubysilverを勉強していたら、よくでてきた配列同士の筆算みたいなのがあったので備忘録にまとめておきます。

a1 = [4,2,3]
a2 = [8,2,3]

p a1 - a2

これを実行するとどうなるでしょう?
結果は「4」です!

Ruby で配列に「-」を使うと、「引き算」=片方の配列から、もう片方に含まれている要素を取り除いた新しい配列」を返すそうです!

どういう仕組みか?
• a1 = [4, 2, 3]
• a2 = [8, 2, 3]
• a1 - a2 は a1からa2に含まれている要素(2と3)を削除した配列
• 残るのは [4] になる

注意点
• - で削除されるのは 値ベース(インデックスじゃない!)
• 同じ要素が複数あっても、a2 にその値が含まれていたら全部消える

例:

p [1,2,2,3] - [2]  
# => [1,3]

簡単に言うと「集合の引き算」みたいなイメージ!

じゃあ今度は「+」を使うとどうなるでしょう

a1 = [1, 2, 3]
a2 = [3, 4, 5]

p a1 + a2
# => [1, 2, 3, 3, 4, 5]

単純に結合するだけ。重複は消えない。
つまり [1,2,3] と [3,4,5] を「つなげた」結果になる!

じゃあ次は「&」の時はどうなるか?

a1 = [1, 2, 3]
a2 = [3, 4, 5]

p a1 & a2
# => [3]

両方に共通する要素だけ取り出す。
いわゆる「共通部分」。a1 かつ a2にある数を取り出すってイメージ。

じゃあ次は「|」の時。これは和集合!

a1 = [1, 2, 3]
a2 = [3, 4, 5]

p a1 | a2
# => [1, 2, 3, 4, 5]

両方の要素をまとめて、重複は除外。
集合の「和集合」そのもの。

まとめ

演算子 意味
+ 単純結合(重複そのまま) [1,2,3] + [3,4][1,2,3,3,4]
- 引き算(差集合) [1,2,3] - [2,3][1]
& 共通部分(積集合) [1,2,3] & [3,4][3]
| 和集合(重複削除) [1,2,3] | [3,4][1,2,3,4]
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?