Class: Remarkovable

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string: string, prefix_length: 2) ⇒ Remarkovable

Returns a new instance of Remarkovable.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/remarkovable.rb', line 4

def initialize(string: string, prefix_length: 2)
  return if string.nil?
  @markov_model = Hash.new { |hash, key| hash[key] = [] }

  words = string.split(/([.!?])|\s+/)
  words.each_with_index do |word, i|
    key = [word]

    (prefix_length - 1).times do |n|
      next_word = i + n + 1
      key << words[next_word]
    end

    key = key.join(' ')
    match = words[i + prefix_length]
    add_triad(key: key, match: match) if i < words.size - prefix_length
  end
end

Instance Attribute Details

#markov_modelObject

Returns the value of attribute markov_model.



2
3
4
# File 'lib/remarkovable.rb', line 2

def markov_model
  @markov_model
end

Instance Method Details

#speak(custom_key: nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/remarkovable.rb', line 23

def speak(custom_key: nil)
  return if @markov_model.nil?
  key = if !custom_key.nil? && @markov_model[custom_key].any?
    custom_key
  else
    @markov_model.keys.sample
  end
  output = Array(key.capitalize.split(' '))

  until (output & %w(. ! ?)).any?
    match = @markov_model[key].sample
    if match.nil?
      key = @markov_model.keys.sample
      next
    end
    output << match
    output.flatten!
    key = [output[-2], output[-1]].join(' ')
  end

  output.join(' ').gsub(/\s+([,.!?])/, '\1')
end