LoginSignup
3
3

More than 5 years have passed since last update.

rubyの配列に非破壊的に値を結合する方法

Last updated at Posted at 2016-12-08

配列に対して破壊的に追加する書き方は良く見るので、非破壊的に追加する方法がなかったので、書いておきます。

前提条件

x = [1, 2, 3]
y = [4, 5]

+

単純に+をする

z = x + y
=> [1, 2, 3, 4, 5]
x
=> [1, 2, 3]

dup

複製する

z = x.dup.concat(y)
=> [1, 2, 3, [4, 5]]
x
=> [1, 2, 3]

代入する

z = [x, y]
=> [[1, 2, 3], [4, 5]]
x
=> [1, 2, 3]

*で展開する

z = [*x, *y]
=> [1, 2, 3, 4, 5]
x
=> [1, 2, 3]

書き方によって後処理が変わる(flattenがいる)と思いますが、こんなもんでしょうか。

他に書き方を知っていれば、教えていただければと思います:bow:

3
3
4

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
3
3