Class: Markov

Inherits:
Object
  • Object
show all
Defined in:
lib/markov.rb,
lib/markov/version.rb

Defined Under Namespace

Modules: VERSION

Instance Method Summary collapse

Constructor Details

#initializeMarkov

Returns a new instance of Markov.



11
12
13
# File 'lib/markov.rb', line 11

def initialize
  @data = {}
end

Instance Method Details

#add(*items) ⇒ Object

Raises:

  • (ArgumentError)


19
20
21
22
23
# File 'lib/markov.rb', line 19

def add(*items)
  raise ArgumentError, 'at least one argument required' if items.empty?
  items.each { |item|  data[item] ||= [] }
  items[0..-2].zip(items[1..-1]).each { |a, b|  data[a].push(b) }
end

#generate(length = 1.0/0) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/markov.rb', line 25

def generate(length = 1.0/0)
  result = []
  items  = data.keys
  while !items.empty? and result.length < length
    item = items.random
    result.push item
    items = data[item]
  end
  result
end

#resetObject



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

def reset
  @data = {}
end