導入
配列を処理するとき、「値」だけでなく「その値が何番目か」も同時に使いたいことがあります。すでに紹介した each_with_index を、他のメソッドと組み合わせて使う場面を見ていきます。
説明
fruits = ["りんご", "バナナ", "ぶどう"]
fruits.each_with_index do |fruit, i|
puts "#{i + 1}番目: #{fruit}"
end
numbers = [1, 2, 3, 4]
labeled = numbers.each_with_index.map { |n, i| "#{i}:#{n}" }
puts labeled.inspect
each_with_index は each と同じく、繰り返すだけなら puts などで十分ですが、.map と組み合わせることで「番号付きの新しい配列」を作ることもできます。この例では each_with_index.map { |n, i| ... } のように、each_with_index の結果をそのまま map に渡しています。
やってみよう
i + 1 の部分を i だけにして、0から始まる番号との違いを確認しましょう。labeled の中身も自分なりの形式に変えてみてください。
演習
配列 names = ["A", "B", "C"] を each_with_index で回し、0: A、1: B、2: C のように表示してください。
ヒント1を見る
names.each_with_index do |name, i| puts "#{i}: #{name}" end のように書きます。
ヒント2を見る
ブロック変数は |値, 番号| の順番です。