Похоже, вы хотите конечный автомат:
require 'statemachine'
state_machine = Statemachine.build do
trans :_, :a, :a
trans :_, :B, :_
trans :a, :a, :aa
trans :a, :B, :aB
trans :aa, :a, :_, 'print 1'
trans :aa, :B, :aB
trans :aB, :a, :_, 'print 2'
trans :aB, :B, :_
end
"aaBaBaaaBaaa".each_char do |i|
state_machine.process_event(i)
end
state_machine.reset
puts
"aaaBaBaaaaBBaBaBa".each_char do |i|
state_machine.process_event(i)
end