Class: Markov::Generate

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dbname, options = {}) ⇒ Generate

Returns a new instance of Generate.



6
7
8
9
10
11
12
# File 'lib/markov/generate.rb', line 6

def initialize dbname, options={}
  @length = options[:length] || 200
  @weight = options[:weight] || 1.2
  @start = options[:start] || "The"
  @table = options[:table]
  @db = DB.new(dbname: dbname, chunk: options[:chunk] || 4)
end

Instance Attribute Details

#lengthObject (readonly)

Returns the value of attribute length.



4
5
6
# File 'lib/markov/generate.rb', line 4

def length
  @length
end

#startObject (readonly)

Returns the value of attribute start.



4
5
6
# File 'lib/markov/generate.rb', line 4

def start
  @start
end

#weightObject (readonly)

Returns the value of attribute weight.



4
5
6
# File 'lib/markov/generate.rb', line 4

def weight
  @weight
end

Instance Method Details

#current_wordObject



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

def current_word
  @current_word = @word || @start
end

#lookup(word, table) ⇒ Object



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

def lookup word, table
  @lookup = @db.lookup(word, table)
  {
    suffices: @lookup.map { |s| s[0] },
    probability: @lookup.map.each_with_index { |c,i|
      [ (c[1].to_i ** @weight).round.times.inject([]){ |r,a| r << i } ]
    }.flatten
  }
end

#next_wordObject



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

def next_word
  word  = current_word.match(/^,/) ? "," : current_word.split(",")[0]
  words = lookup(CGI.escape(word), @table)
  index = words[:probability].sample
  @word = CGI.unescape(words[:suffices][index])
end

#textObject



35
36
37
38
39
40
# File 'lib/markov/generate.rb', line 35

def text
  (0..@length).inject("#@start "){ |r,a|
    next_word
    r << "#{current_word.match(/^,/) ? "," : current_word.split(",")[0]} "
  }.strip.squeeze(" ").gsub(/\s(\.|\,|:|;|`|'|\?|!)/,"\\1")
end