Skip to content

Instantly share code, notes, and snippets.

@stalcottsmith
Created March 12, 2010 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stalcottsmith/330917 to your computer and use it in GitHub Desktop.
Save stalcottsmith/330917 to your computer and use it in GitHub Desktop.
module Abbreviator
def self.abbreviate(names)
abbrs = names.sort.inject({}) do |hash, name|
hash[name] = replace_non_word_chars(name).slice(0,3)
hash
end
Hash[*abbrs.map do |name, abbr|
[name,
(abbrs.values.select{|v|v.eql?(abbr)}.size == 1) ? abbr :
resolve_conflict(abbr, name, [abbrs.select{|k,v| v.eql?(abbr)}.map(&:first)-[name]].flatten)]
end.flatten]
end
private
def self.replace_non_word_chars(s)
s.gsub(/\W/, '')
end
def self.resolve_conflict(abbr, name, conflicts)
conflict_chars = conflicts.map {|c| replace_non_word_chars(c).split('')}
abbr + (replace_non_word_chars(name).split('').detect do |char|
!conflict_chars.map {|c| c.shift}.include?(char)
end || '')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment