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?

More than 3 years have passed since last update.

[Ruby] eachとmapの違い

Posted at

eachとmapの違いについてまとめました.
#each
繰り返し処理を行う際に使用する.ただ,戻り値は繰り返し処理の前の値となる.

###使用例

array = [1, 5]
array.each do |item|
  item * 2
end
2
10
=> [1, 5]

#map
繰り返し処理の結果を配列として保持したい場合に使用する.

###使用例

array = [1, 5]
result = array.map do |item|
  item * 2
end
=>[2, 10]

#mapをeachに書き換える方法

array = [1, 5]
result = []
array.each do |item|
  result << item * 2
end
=>[2, 10]

上記のように書き換えるとeachでmapと同じ処理を実行することができるようになる.
しかし,mapに比べると記述量が多くなってしまうので,繰り返し処理の結果を使用する際はmapで記述するようにする.

#参考リンク
【Ruby】eachとmapの違い

0
0
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
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?