Sentinel+run_detection.rb
This content was produced by an LLM and could include errors.
このスクリプトは空文字列を区切りとして配列をグループ化し、番兵 'END' で終了を判定しながら各グループの要素数を集計します。ラベルは次の非空要素まで引き継がれ、出力は ONE: 3 / TWO: 2 / THREE: 4 となります。ループ・カウンタ・ラベル更新を手書きするステートマシン的な処理の練習例です。
# frozen_string_literal: true
#=> nil
seq = ['ONE', '', '', 'TWO', '', 'THREE', '', '', '',]
#=> ["ONE", "", "", "TWO", "", "THREE", "", "", ""]
seq.push('END')
#=> ["ONE", "", "", "TWO", "", "THREE", "", "", "", "END"]
count = 0
#=> 0
label = ''
#=> ""
index = 0
#=> 0
loop do
current = seq[index]
label = current unless current.empty?
# processing 1
count += 1
next_value = seq[index + 1]
unless next_value.empty?
# processing 2
puts "#{label}: #{count}"
break if next_value.eql?('END')
# initialize
count = 0
end
index += 1
end
ONE: 3
TWO: 2
THREE: 4
#=> nil
Ruby 4.0.6