29
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Ruby]配列の足し算・引き算・掛け算・和集合・積集合

Last updated at Posted at 2019-04-02

Rubyの配列同士の演算

  • Rubyは配列同士で足したり引いたりできてとても便利。

環境

  • Ruby 2.6.0

足し算

a = [1, 2, 3]
b = [3, 4, 5]
p a + b # => [1, 2, 3, 3, 4, 5]
  • 右の配列の要素を左の配列の要素の後ろにそのまま追加する
  • a += b みたいに破壊的な使い方もできる

引き算

a = [1, 2, 3]
b = [3, 4, 5]
p a - b # => [1, 2]
  • 左の配列の要素から共通する要素を除外する
  • 右の配列が左の配列に無い要素を持っていても無視される
  • a -= b みたいに破壊的な使い方もできる

掛け算

a = [1, 2, 3]
p a * 2 # => [1, 2, 3, 1, 2, 3]
  • 同じ要素を繰り返した新しい配列を作る
  • ちなみに割り算はできない

和集合

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

c = [6, 6, 6, 7]
p b | c # => [3, 4, 5, 6, 7]
  • 左右の配列を結合して重複を除外する( (a + b).uniq と同じ)
  • 元の配列に重複する要素があっても除外される
  • 変な使い方をすると [1, 2, 2, 3] | [][1, 2, 2, 3].uniq と同じ

積集合

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

c = [5, 5, 6]
p b & c # => [5]
  • 左右の配列の共通する要素のみ取り出して重複を除外する
  • 元の配列に重複する要素があっても除外される

意外と便利なので、色んなところで使ってみるとコードを節約できるかも。

29
14
1

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
29
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?