Class: Mrkv::Chain

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

Instance Method Summary collapse

Constructor Details

#initialize(ngram = 2) ⇒ Chain

Returns a new instance of Chain.


5
6
7
8
# File 'lib/mrkv.rb', line 5

def initialize ngram=2
  @ngram = ngram
  @chain = Hash.new { |h,k| h[k] = [] }
end

Instance Method Details

#add(lines) ⇒ Object


10
11
12
13
14
15
16
17
18
19
# File 'lib/mrkv.rb', line 10

def add lines
  lines.each do |line|
    line.downcase.capitalize.gsub(/[^a-zA-Z0-9\.\!\?\s]/, '').split.each_cons(@ngram + 1) do |link|
      next if link.nil?
      @chain[link.take(@ngram).join(" ")] << link.last
    end
  end
  @starters = @chain.keys.select{|k| k =~ /^[A-Z]/}
  true
end

#generateObject


21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mrkv.rb', line 21

def generate
  random_starter.split.tap do |str_arr|
    until str_arr.last.match /[\?\!\.]$/
      possibilities = @chain[str_arr[-@ngram..-1].join(" ")]
      if !possibilities.empty?
        str_arr << possibilities.sample
      else
        str_arr.last << ["?", "!", "."].sample
      end
    end
  end.join(" ")
end