Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Metaphone calculation

// Calculate's Lawrence Phillip's basic metaphone (a more advanced code for matching names)

   1  
   2  class Metaphone
   3    TRANSFORMATIONS = [[/\A[gkp]n/  ,  'n'],   # gn, kn, or pn at the start turns into 'n'
   4                       [/\Ax/       ,  's'],   # x at the start turns into 's'
   5                       [/\Awh/      ,  'w'],   # wh at the start turns into 'w'
   6                       [/mb\z/      ,  'm'],   # mb at the end turns into 'm'
   7                       [/sch/       ,  'sk'],  # sch sounds like 'sk'
   8                       [/x/         ,  'ks'],
   9                       [/cia/       ,  'xia'], # the 'c' -cia- and -ch- sounds like 'x'
  10                       [/ch/        ,  'xh'],
  11                       [/c([iey])/  ,  's\1'], # the 'c' -ce-, -ci-, or -cy- sounds like 's'
  12                       [/ck/        ,  'k'],
  13                       [/c/         ,  'k'],
  14                       [/dg([eiy])/ ,  'j\1'], # the 'dg' in -dge-, -dgi-, or -dgy- sounds like 'j'
  15                       [/d/         ,  't'],
  16                       [/gh/        ,  ''],
  17                       [/gned/      ,  'ned'],
  18                       [/gn((?![aeiou])|(\z))/ ,  'n'],
  19                       [/g[eiy]/    ,  'j'],
  20                       [/ph/        ,  'f'],
  21                       [/[aeiou]h(?![aeoiu])/ ,  '\1'], # 'h' is silent after a vowel unless it's between vowels
  22                       [/q/         ,  'k'],
  23                       [/s(h|(ia)|(io))/ ,  'x\1'],
  24                       [/t((ia)|(io))/,  'x\1'],
  25                       [/th/        ,  '0'],
  26                       [/v/         ,  'f'],
  27                       [/w(?![aeiou])/ ,  ''],
  28                       [/y(?![aeiou])/ ,  ''],
  29                       [/z/         ,  's']
  30                      ]
  31                      
  32    def self.create_metaphone(aWord)
  33      word = aWord.to_s.downcase
  34      TRANSFORMATIONS.each{|transform| word.gsub!(transform.first, transform.last)}
  35      'a'.upto('z'){|letter| word.gsub!(letter*2, letter)}
  36      return (word[0].chr + word[1..word.length-1].gsub(/[aeiou]/, '')).upcase
  37    end
  38  end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS