// algorithm discussed at http://en.wikipedia.org/wiki/Soundex
// It's wrapped in a class primarily to contain the ALPHA_MAP.
class Soundex ALPHA_MAP = { 'a' => nil, 'b' => '1', 'c' => '2', 'd' => '3', 'e' => nil, 'f' => '1', 'g' => '2', 'h' => nil, 'i' => nil, 'j' => '2', 'k' => '2', 'l' => '4', 'm' => '5', 'n' => '5', 'o' => nil, 'p' => '1', 'q' => '2', 'r' => '6', 's' => '2', 't' => '3', 'u' => nil, 'v' => '1', 'w' => nil, 'x' => '2', 'y' => nil, 'z' => 2 } def self.calculate(aName) ary = [] # map all the letters in the supplied name aName.downcase.each_byte{|ltr| ary.push(ALPHA_MAP[ltr.chr])} # now drop out repeated values ary.length.downto(1){ |idx| ary[idx] = nil if ary[idx]==ary[idx-1] } # remove the nil elements ary.compact! # pad with zeroes 0.upto(2){ ary.push('0')} # Replace the first value with the first letter of the supplied name ary[0] = aName[0].chr # return the first four elements of the array as a string return ary[0..3].to_s end end