Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | 配列 | indexを使用しながらイテレーターを利用する

パンくず

Ruby
配列
indexを使用しながらイテレーターを利用する

概要

Rubyの配列に対し、イテレーターを使用して各要素にアクセスしつつ
indexも取得する方法について

構文

array.each_with_index {|value,index|expression}

サンプル

# -*- encoding: utf-8 -*-
require "pp"

array = [1,2,3]
array.each_with_index {|value, index|
  pp "array[#{index}]=#{value}"
}

出力

"array[0]=1"
"array[1]=2"
"array[2]=3"