制御構造内で配列からキーと値を抜き出す

配列からキーと値を抜き出すの解決例。

ソース

array_sample.rb として保存。

counter = ['zero', 'first', 'second', 'third', 'forth', 'fifth']

# Enumerable クラスの each_with_index メソッド
counter.each_with_index do |value, index|
  puts "#{index}: #{value}"
end

puts

# Integer クラスの uptp メソッド の場合
0.upto(counter.length - 1) do |i|
  puts "#{i}: #{counter[i]}"
end

実行結果

% ruby array_sample.rb
0: zero
1: first
2: second
3: third
4: forth
5: fifth

0: zero
1: first
2: second
3: third
4: forth
5: fifth

1行で書くと、%w(zero first second third forth fifth).each_with_index{|i,idx| puts "#{idx}: #{i}"} で同じ結果になりますよ。putsは改行がなければ改行を付けて、ある場合はそのまま表示するので"\n"は不要になります。
id:tks_period

アドバイスに感謝です。