3
1

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.

eachとmapの違い

3
Last updated at Posted at 2019-08-17

結論

each元の配列
map処理後の配列

を返します。

具体例

例として、1〜3にそれぞれ1を足すとします。

eachの場合、返り値は元の配列になるので、[1, 2, 3]になります。
処理結果を取得する場合、eachブロック外で変数を定義(num = [])し、ブロック内で保存する必要があります。

num = [] 
[1, 2, 3].each do |i|
 # ブロック内で保存
 num <<  i + 1
end

# =>[2, 3, 4]

一方mapの場合、返り値は処理結果の配列となります。
そのまま使用することができるので、以下の場合は[2, 3, 4]となります。

[1, 2, 3].map do |i|
  i + 1
end

# =>[2, 3, 4]
3
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?