はじめに
Ruby Silverの取得を目指して勉強中です。
アウトプットとして、each_with_indexメソッドについてまとめます。
each_with_index とは
-
eachと同じように配列の要素を順番に取り出す - さらに「番号(index)」も一緒に渡してくれる
- 何番目の要素なのか」を知りたい時に便利
なぜ each_with_index が必要なのか
普通の each だと
a = ["soccer", "baseball", "tennis", "basketball"]
a.each do |item|
puts item
end
これだと要素の内容しかわからず、「何番目なのか」がわからない
each_with_index を使う
a = ["soccer", "baseball", "tennis", "basketball"]
a.each_with_index do |item, i|
puts "#{i}番目: #{item}"
end
要素と一緒に「位置」もわかる
実際のコード
a = ["soccer", "baseball", "tennis", "basketball"]
a.each_with_index do |item, i|
print i, ":", item, "\n"
end
出力結果
0:soccer
1:baseball
2:tennis
3:basketball
重要なポイント
-
i→ 位置(0から始まる番号) -
item→ その位置の要素 - プログラミングでは番号は0から始まる
もう少しわかりやすく
配列を表にして考えると以下のようになる
| index | 要素 |
|---|---|
| 0 | soccer |
| 1 | baseball |
| 2 | tennis |
| 3 | basketball |
each_with_index は、「index と要素」をペアにして順番に渡してくれる
メモ
番号と要素をまとめて表示するなら、こんな風にも書ける
a.each_with_index do |item, i|
puts "#{i}: #{item}"
end
出力は同じ
よくある使用例
1. 順位を表示する
sports = ["soccer", "baseball", "tennis", "basketball"]
sports.each_with_index do |sport, i|
puts "第#{i + 1}位: #{sport}"
end
出力:
第1位: soccer
第2位: baseball
第3位: tennis
第4位: basketball
2. 条件に応じて処理を変える
sports = ["soccer", "baseball", "tennis", "basketball"]
sports.each_with_index do |sport, i|
if i == 0
puts "優勝: #{sport}"
elsif i < 3
puts "入賞: #{sport}"
else
puts "参加賞: #{sport}"
end
end
3. 偶数番目だけ処理する
sports = ["soccer", "baseball", "tennis", "basketball"]
sports.each_with_index do |sport, i|
if i.even? # 偶数番目(0, 2, 4...)
puts "偶数番目: #{sport}"
end
end
コツ
以下の場合、変数名は意味がわかりやすいものにした方が良さそう
# 良い例
sports.each_with_index do |sport, index|
# 悪い例(意味がわからない)
sports.each_with_index do |x, y|
まとめ
each_with_indexは配列の要素と一緒に「位置」も知りたい時に使う便利なメソッド
- 順位表示
- 条件分岐
- 特定の位置だけ処理
初学者のため、間違えていたらすいません。