Sha256: 8c4cd621769e7ffb3d3b5847a9a02343812231234841bc8d7e319cd20f45d34e

Contents?: true

Size: 1.02 KB

Versions: 4

Compression:

Stored size: 1.02 KB

Contents

require 'phonetic/algorithm'

module Phonetic
  # Soundex phonetic algorithm was developed by Robert C. Russell and Margaret K. Odell.
  # This class implements American Soundex version of algorithm.
  #
  # @example
  #    Phonetic::Soundex.encode('Ackerman') # => 'A265'
  #    Phonetic::Soundex.encode('ammonium') # => 'A500'
  #    Phonetic::Soundex.encode('implementation') # => 'I514'
  class Soundex < Algorithm
    CODE = {
      B: 1, P: 1, F: 1, V: 1,
      C: 2, S: 2, K: 2, G: 2, J: 2, Q: 2, X: 2, Z: 2,
      D: 3, T: 3,
      L: 4,
      M: 5, N: 5,
      R: 6
    }

    # Convert word to its Soundex code
    def self.encode_word(word, options = {})
      return '' if word.empty?
      w = word.upcase
      res = w[0]
      pg = CODE[w[0].to_sym]
      (1...w.size).each do |i|
        g = CODE[w[i].to_sym]
        if g and pg != g
          res += g.to_s
          pg = g
        end
        break if res.size > 3
      end
      res = res.ljust(4, '0')
      res
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
phonetic-1.2.0 lib/phonetic/soundex.rb
phonetic-1.1.0 lib/phonetic/soundex.rb
phonetic-1.0.1 lib/phonetic/soundex.rb
phonetic-1.0.0 lib/phonetic/soundex.rb