class Ipsumizer

Constants

DEFAULT_PREFIX
DEFAULT_SENTENCER
VERSION

Attributes

prefix[R]
sentencer[R]

Public Class Methods

new( sentences, prefix: DEFAULT_PREFIX, sentencer: DEFAULT_SENTENCER ) click to toggle source
# File lib/ipsumizer.rb, line 10
def initialize( sentences, prefix: DEFAULT_PREFIX, sentencer: DEFAULT_SENTENCER )
  @prefix = prefix.to_i
  fail "prefix length must be non-negative: #{prefix}" unless prefix > 0
  @sentencer = sentencer
  @transitions = {}
  if sentences.is_a? String
    sentences = sentence sentences
  end
  sentences = sentences.map{ |s| s.strip.gsub /\s/, ' ' }.select{ |s| s =~ /\S/ }
  fail "no sentences" unless sentences.any?
  sentences.each do |s|
    key = ''
    i = 0
    (0..s.length).each do |i|
      nxt = if i == s.length
        nil
      else
        s[i]
      end
      counts = @transitions[key] ||= {}
      counts[nxt] = counts[nxt].to_i + 1
      if nxt
        key += nxt
        if key.length > prefix
          key = key[1..-1]
        end
      end
    end
  end
  @transitions.each do |pfx, counts|
    total = counts.values.reduce(:+)
    probabilities = counts.values.map{ |n| n.to_r / total }
    @transitions[pfx] = AliasTable.new( counts.keys, probabilities )
  end
end

Public Instance Methods

sentence(text) click to toggle source

split a text into sentences, where sentences are separated by on of '.', '!', and '?', optionally preceded by double quotes or closing brackets and so forth

# File lib/ipsumizer.rb, line 48
def sentence(text)
  text.split(sentencer).each_slice(2).map{ |*bits| bits.join }.select{ |s| s =~ /\S/ }
end
speak() click to toggle source

make a random sentence

# File lib/ipsumizer.rb, line 53
def speak
  pfx = s = ''
  loop do
    nxt = @transitions[pfx]&.generate
    break unless nxt
    s += nxt
    pfx += nxt
    if pfx.length > prefix
      pfx = pfx[1..-1]
    end
  end
  s
end