Module Gem::Text
In: lib/rubygems/text.rb

A collection of text-wrangling methods

Methods

Public Instance methods

Wraps text to wrap characters and optionally indents by indent characters

[Source]

    # File lib/rubygems/text.rb, line 12
12:   def format_text(text, wrap, indent=0)
13:     result = []
14:     work = text.dup
15: 
16:     while work.length > wrap do
17:       if work =~ /^(.{0,#{wrap}})[ \n]/ then
18:         result << $1
19:         work.slice!(0, $&.length)
20:       else
21:         result << work.slice!(0, wrap)
22:       end
23:     end
24: 
25:     result << work if work.length.nonzero?
26:     result.join("\n").gsub(/^/, " " * indent)
27:   end

This code is based directly on the Text gem implementation Returns a value representing the "cost" of transforming str1 into str2

[Source]

    # File lib/rubygems/text.rb, line 31
31:   def levenshtein_distance str1, str2
32:     s = str1
33:     t = str2
34:     n = s.length
35:     m = t.length
36:     max = n/2
37: 
38:     return m if (0 == n)
39:     return n if (0 == m)
40:     return n if (n - m).abs > max
41: 
42:     d = (0..m).to_a
43:     x = nil
44: 
45:     n.times do |i|
46:       e = i+1
47: 
48:       m.times do |j|
49:         cost = (s[i] == t[j]) ? 0 : 1
50:         x = [
51:              d[j+1] + 1, # insertion
52:              e + 1,      # deletion
53:              d[j] + cost # substitution
54:             ].min
55:         d[j] = e
56:         e = x
57:       end
58: 
59:       d[m] = x
60:     end
61: 
62:     return x
63:   end

[Validate]