@example.each do |e|
#do something here
end
ここで、それぞれの最初と最後の要素で何か違うことをしたいのですが、どうすればこれを達成できますか? 確かに、ループ変数 i を使用して追跡できi==0
ますi==@example.size
。
@example.each do |e|
#do something here
end
ここで、それぞれの最初と最後の要素で何か違うことをしたいのですが、どうすればこれを達成できますか? 確かに、ループ変数 i を使用して追跡できi==0
ますi==@example.size
。
インデックスを使用each_with_index
して、最初と最後のアイテムを識別できます。例えば:
@data.each_with_index do |item, index|
if index == 0
# this is the first item
elsif index == @data.size - 1
# this is the last item
else
# all other items
end
end
または、配列の「中間」を次のように分離することもできます。
# This is the first item
do_something(@data.first)
@data[1..-2].each do |item|
# These are the middle items
do_something_else(item)
end
# This is the last item
do_something(@data.last)
これらの方法では、リストに項目が 1 つまたは 2 つしかない場合の望ましい動作に注意する必要があります。
かなり一般的なアプローチは次のとおりです (配列に重複がまったくない場合)。
@example.each do |e|
if e == @example.first
# Things
elsif e == @example.last
# Stuff
end
end
配列に重複が含まれている可能性があると思われる場合 (または単にこの方法を好む場合) は、配列から最初と最後の項目を取得し、それらをブロックの外で処理します。このメソッドを使用する場合、各インスタンスで動作するコードを関数に抽出して、繰り返す必要がないようにする必要があります。
first = @example.shift
last = @example.pop
# @example no longer contains those two items
first.do_the_function
@example.each do |e|
e.do_the_function
end
last.do_the_function
def do_the_function(item)
act on item
end