4 # Copyright (c) 2001,2003 Akinori MUSHA <knu@iDaemons.org>
6 # All rights reserved. You can redistribute and/or modify it under
7 # the same terms as Ruby.
9 # $Idaemons: /home/cvs/rb/abbrev.rb,v 1.2 2001/05/30 09:37:45 knu Exp $
10 # $RoughId: abbrev.rb,v 1.4 2003/10/14 19:45:42 knu Exp $
11 # $Id: abbrev.rb 11708 2007-02-12 23:01:19Z shyouhei $
14 # Calculate the set of unique abbreviations for a given set of strings.
19 # pp Abbrev::abbrev(['ruby', 'rules']).sort
29 # Also adds an +abbrev+ method to class +Array+.
33 # Given a set of strings, calculate the set of unambiguous
34 # abbreviations for those strings, and return a hash where the keys
35 # are all the possible abbreviations and the values are the full
36 # strings. Thus, given input of "car" and "cone", the keys pointing
37 # to "car" would be "ca" and "car", while those pointing to "cone"
38 # would be "co", "con", and "cone".
40 # The optional +pattern+ parameter is a pattern or a string. Only
41 # those input strings matching the pattern, or begging the string,
42 # are considered for inclusion in the output hash
44 def abbrev(words, pattern = nil)
48 if pattern.is_a?(String)
49 pattern = /^#{Regexp.quote(pattern)}/ # regard as a prefix
53 next if (abbrev = word).empty?
54 while (len = abbrev.rindex(/[\w\W]\z/)) > 0
57 next if pattern && pattern !~ abbrev
59 case seen[abbrev] += 1
71 next if pattern && pattern !~ word
79 module_function :abbrev
83 # Calculates the set of unambiguous abbreviations for the strings in
84 # +self+. If passed a pattern or a string, only the strings matching
85 # the pattern or starting with the string are considered.
87 # %w{ car cone }.abbrev #=> { "ca" => "car", "car" => "car",
88 # "co" => "cone", "con" => cone",
90 def abbrev(pattern = nil)
91 Abbrev::abbrev(self, pattern)
97 hash = line.split.abbrev
99 hash.sort.each do |k, v|