Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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