Class: MarkovUuid::Chain

Inherits:
Hash
  • Object
show all
Defined in:
lib/markov_uuid/chain.rb

Constant Summary collapse

SEPARATOR =
"#-#-"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(h = {}) ⇒ Chain

Returns a new instance of Chain.



20
21
22
# File 'lib/markov_uuid/chain.rb', line 20

def initialize h={}
  replace h
end

Instance Attribute Details

#wordsObject (readonly)

Returns the value of attribute words.



4
5
6
# File 'lib/markov_uuid/chain.rb', line 4

def words
  @words
end

Class Method Details

.from_string(string) ⇒ Object



7
8
9
# File 'lib/markov_uuid/chain.rb', line 7

def from_string string
  from_word_list(strip_punctuation string)
end

.from_word_list(words) ⇒ Object



11
12
13
# File 'lib/markov_uuid/chain.rb', line 11

def from_word_list words
  new.tap { |i| i.add words }
end

.strip_punctuation(l) ⇒ Object



15
16
17
# File 'lib/markov_uuid/chain.rb', line 15

def strip_punctuation l
  l.gsub(/[[:punct:]]/," ").gsub('  ', ' ').split " "
end

Instance Method Details

#add(words) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/markov_uuid/chain.rb', line 24

def add words
  key = SEPARATOR

  words.each do |word|
    (self[key] ||= []) << word

    key = new_key(key, word)
  end
end

#format(result, i = 32) ⇒ Object



56
57
58
59
60
61
# File 'lib/markov_uuid/chain.rb', line 56

def format result, i=32
  result.join("-")[0..i.to_i].
    gsub(/\A\w+-/ , "").
    gsub(/-$/     , "").
    gsub(/-\w+$/  , "")
end

#new_key(key, word) ⇒ Object



34
35
36
37
38
# File 'lib/markov_uuid/chain.rb', line 34

def new_key(key, word)
  return SEPARATOR if word == "\n"

  word or key
end

#uuid(length = 100) ⇒ Object

note these are not by any means guaranteed to be unique dependent on uuid length and corpus size maybe maintain uniqueness elsewhere by regenerating unless unique



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/markov_uuid/chain.rb', line 43

def uuid length = 100
  key = keys.sample
  word = ""

  result = length.times.map do
    word = self[key].sample rescue nil
    key = new_key key, word
    word
  end.compact

  format result
end