Module Abbrev
In: lib/abbrev.rb

Calculate the set of unique abbreviations for a given set of strings.

  require 'abbrev'
  require 'pp'

  pp Abbrev::abbrev(['ruby', 'rules']).sort

Generates:

  [["rub", "ruby"],
   ["ruby", "ruby"],
   ["rul", "rules"],
   ["rule", "rules"],
   ["rules", "rules"]]

Also adds an abbrev method to class Array.

Methods

abbrev  

Public Instance methods

Given a set of strings, calculate the set of unambiguous abbreviations for those strings, and return a hash where the keys are all the possible abbreviations and the values are the full strings. Thus, given input of "car" and "cone", the keys pointing to "car" would be "ca" and "car", while those pointing to "cone" would be "co", "con", and "cone".

The optional pattern parameter is a pattern or a string. Only those input strings matching the pattern, or begging the string, are considered for inclusion in the output hash

[Source]

    # File lib/abbrev.rb, line 44
44:   def abbrev(words, pattern = nil)
45:     table = {}
46:     seen = Hash.new(0)
47: 
48:     if pattern.is_a?(String)
49:       pattern = /^#{Regexp.quote(pattern)}/     # regard as a prefix
50:     end
51: 
52:     words.each do |word|
53:       next if (abbrev = word).empty?
54:       while (len = abbrev.rindex(/[\w\W]\z/)) > 0
55:         abbrev = word[0,len]
56: 
57:         next if pattern && pattern !~ abbrev
58: 
59:         case seen[abbrev] += 1
60:         when 1
61:           table[abbrev] = word
62:         when 2
63:           table.delete(abbrev)
64:         else
65:           break
66:         end
67:       end
68:     end
69: 
70:     words.each do |word|
71:       next if pattern && pattern !~ word
72: 
73:       table[word] = word
74:     end
75: 
76:     table
77:   end

[Validate]