Class: Gabbler

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

Overview

Copyright © 2011 Michael Dvorkin

Gabbler is freely distributable under the terms of MIT license. See LICENSE file or www.opensource.org/licenses/mit-license.php


Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Gabbler

Returns a new instance of Gabbler.



15
16
17
18
# File 'lib/gabbler/generator.rb', line 15

def initialize(options = {})
  @depth = options[:depth] || 2
  unlearn!
end

Class Method Details

.versionObject



7
8
9
# File 'lib/gabbler/version.rb', line 7

def self.version
  '0.1.0'
end

Instance Method Details

#learn(text) ⇒ Object

Split text into sentences and add them all to the dictionary.




22
23
24
25
26
# File 'lib/gabbler/generator.rb', line 22

def learn(text)
  text.split(/([.!?])/).each_slice(2) do |sentence, terminator|
    add_to_dictionary(sentence, terminator || '.')
  end
end

#sentenceObject

Generate one pseudo-random sentence.




36
37
38
39
40
41
42
# File 'lib/gabbler/generator.rb', line 36

def sentence
  words = @start.sample # Pick random word, then keep appending connected words.
  while next_word = next_word_for(words[-@depth, @depth])
    words << next_word
  end
  words[0..-2].join(" ") + words.last             # Format the sentence.
end

#unlearn!Object

Reset internal data in case one needs to re-learn new training set.




30
31
32
# File 'lib/gabbler/generator.rb', line 30

def unlearn!
  @dictionary, @start = {}, []
end