each_with_index each_with_indexを使うと、インデックスもわかりつつ、配列の要素すべてにアクセスができる list = [1,12,34,14,5,6] list.each_with_index{|elem, i| print i+1, "番目の要素は", elem, "です\n" } 結果 1番目の要素は1です 2番目の要素は12です 3番目の要素は34です 4番目の要素は14です 5番目の要素は5です 6番目の要素は6です
each_with_indexを使うと、インデックスもわかりつつ、配列の要素すべてにアクセスができる
list = [1,12,34,14,5,6] list.each_with_index{|elem, i| print i+1, "番目の要素は", elem, "です\n" }
結果
1番目の要素は1です 2番目の要素は12です 3番目の要素は34です 4番目の要素は14です 5番目の要素は5です 6番目の要素は6です
indexを取りつつのeach