Class: TuringMachine::Tape

Inherits:
Object
  • Object
show all
Defined in:
lib/turing_machine/tape.rb

Overview

Public: The tape of a Turing machine, combined with the head.

Constant Summary collapse

BLANK_SYMBOL =
'0'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = BLANK_SYMBOL) ⇒ Tape

Returns a new instance of Tape.



8
9
10
11
# File 'lib/turing_machine/tape.rb', line 8

def initialize(data = BLANK_SYMBOL)
  @symbols = data.scan(/./)
  @index = 0
end

Instance Attribute Details

#indexObject (readonly)

Returns the value of attribute index.



13
14
15
# File 'lib/turing_machine/tape.rb', line 13

def index
  @index
end

Instance Method Details

#headObject



15
16
17
# File 'lib/turing_machine/tape.rb', line 15

def head
  @symbols[@index]
end

#head=(symbol) ⇒ Object



19
20
21
# File 'lib/turing_machine/tape.rb', line 19

def head=(symbol)
  @symbols[@index] = symbol
end

#shift_leftObject

Public: Move the head to the left.



24
25
26
27
28
29
30
# File 'lib/turing_machine/tape.rb', line 24

def shift_left
  if @index == 0
    @symbols.unshift(BLANK_SYMBOL)
  else
    @index -= 1
  end
end

#shift_rightObject

Public: Move the head to the right.



33
34
35
36
# File 'lib/turing_machine/tape.rb', line 33

def shift_right
  @symbols.push(BLANK_SYMBOL) if @index == @symbols.size - 1
  @index += 1
end

#to_sObject



38
39
40
# File 'lib/turing_machine/tape.rb', line 38

def to_s
  @symbols.join
end