Class: BabyBots::State

Inherits:
Object
  • Object
show all
Defined in:
lib/baby_bots/state.rb

Overview

The state contained within the BabyBots Finite State Automata. States have an event that transitions to a new state. They may also have an event named :else which will be the transition used by the containing BabyBot when calculating transitions where no such supplied events exist.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(state, table = {}) ⇒ State

Sets the state name, as well as an optionally supplied transition table.



17
18
19
20
21
22
23
# File 'lib/baby_bots/state.rb', line 17

def initialize(state, table={})
  # state name
  @state = state
  
  # transition table
  @table = table
end

Instance Attribute Details

#stateObject (readonly)

Returns the value of attribute state.



14
15
16
# File 'lib/baby_bots/state.rb', line 14

def state
  @state
end

#tableObject (readonly)

Returns the value of attribute table.



14
15
16
# File 'lib/baby_bots/state.rb', line 14

def table
  @table
end

Instance Method Details

#==(another_state) ⇒ Object

Equality is based on the same transition table.



51
52
53
# File 'lib/baby_bots/state.rb', line 51

def ==(another_state)
  if @table == another_state.table then return true else return false end
end

#add_transition(event, transition) ⇒ Object

Adds a transition to the transition table. Table format is event => transition, where event is the “input” into the state. Transitions are allowed to be deleted by being set to NOWHERE.



28
29
30
31
32
33
34
# File 'lib/baby_bots/state.rb', line 28

def add_transition(event, transition)
  if transition == NOWHERE
    remove_transition(event)
  else
    @table[event] = transition
  end
end

#build(table) ⇒ Object

Provided a table, merge the state’s current transition table with the supplied one. Note that since this is part of a finite state machine, supplying events that already exist in the transition table override this transition.



40
41
42
# File 'lib/baby_bots/state.rb', line 40

def build(table)
  table.each { |k,v| add_transition(k, v) }
end

#remove_transition(event) ⇒ Object

Delete an entry from the transition table.



46
47
48
# File 'lib/baby_bots/state.rb', line 46

def remove_transition(event)
  @table.delete(event)
end