3
3

More than 5 years have passed since last update.

2つの配列の各要素を足して新しい配列を作成する

Posted at

Ruby で
[1, 6, 4, 3, 6] + [5, 4, 3, 2, 1] = [6, 10, 7, 5, 7]
をやる一つの方法。

ary1 = [1, 6, 4, 3, 6]
ary2 = [5, 4, 3, 2, 1]

ary1.zip(ary2).map {|a, b| a + b} # => [6, 10, 7, 5, 7]

「n個の配列の各要素をそれぞれ〇〇した配列を作成」には、ほとんどの場合 .zip.map が使える。

3
3
0

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