2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

map, each, inject, each_with_objectの使い分け

Last updated at Posted at 2025-01-24

1. map - 配列の変換に特化

mapメソッドは、配列の各要素を新しい値に変換して、新しい配列を生成。元の配列は変更されず、変換後の新しい配列が返される。

numbers = [1, 2, 3]
doubled = numbers.map { |n| n * 2 }
# => [2, 4, 6]

names = ['john', 'jane', 'bob']
uppercased = names.map(&:upcase)
# => ['JOHN', 'JANE', 'BOB']

使用すべき場面:

・配列の各要素に同じ処理を適用して変換したい
・元の配列と同じ長さの新しい配列が必要

2.each - シンプルな繰り返し処理

eachは最もシンプルな繰り返し処理を行うメソッド。各要素に対して処理を実行、戻り値は元の配列。

numbers = [1, 2, 3]
numbers.each { |n| puts n }
# 出力:
# 1
# 2
# 3
# => [1, 2, 3]  # 戻り値は元の配列

users = ['John', 'Jane']
users.each do |user|
  puts "Hello, #{user}!"
end

使用すべき場面:

・各要素に対して単純な処理を行いたい
・表示やログ出力など、副作用のある処理を実行したい
・戻り値が不要な処理を行う

3. inject - 値の集約

injectは、要素を順番に処理して1つの値にまとめる。累積的な計算や要素の集約に適している。

# 合計値の計算
numbers = [1, 2, 3, 4]
sum = numbers.inject(0) { |result, n| result + n }
# => 10

# 文字列の連結
words = ['Hello', 'World']
message = words.inject('') { |result, word| result + word + ' ' }
# => "Hello World "

# 最大値の検索
numbers = [3, 7, 2, 9, 4]
max = numbers.inject { |max, n| max > n ? max : n }
# => 9

使用すべき場面:

・配列の要素を1つの値に集約したい
・合計、積算、最大値/最小値の計算
・要素を順番に処理して結果を蓄積する

4. each_with_object - オブジェクトの構築

each_with_objectは、繰り返し処理をしながら任意のオブジェクトを構築できる。特にハッシュの作成や複雑なデータ構造の構築に便利。

numbers = [1, 2, 3]
result = numbers.each_with_object({}) do |num, hash|
  hash[num] = num * 2
end
# => {1=>2, 2=>4, 3=>6}

使用すべき場面:

・ハッシュなど、配列以外のオブジェクトを作成したい
・データの集計や分類が必要
・複雑なデータ構造を構築する

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?