0
0

each_with_indexメソッド

Posted at

each_with_indexメソッドを用いると、繰り返し処理の中で、配列の添え字も扱うことができる。

animals = ["dog", "cat", "fox"]

animals.each_with_index do |animal,index|
  puts "#{index}:#{animal}"
end

これを実行すると、以下の結果になる。

0:dog
1:cat
2:fox

スタートを1からにしたい場合はindex+1とすると1から始めることができる。

animals = ["dog", "cat", "fox"]

animals.each_with_index do |animal,index|
  puts "#{index + 1}:#{animal}"
end
1:dog
2:cat
3:fox
0
0
0

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