Sha256: fb9fb9070baf12ba43f72ac2cfaf21c02009c08e54cdcc182794485bd4809a55

Contents?: true

Size: 1.28 KB

Versions: 11

Compression:

Stored size: 1.28 KB

Contents

#
# Ruby implementation of the Soundex algorithm,
# as described by Knuth in volume 3 of The Art of Computer Programming.
#
# Author: Michael Neumann (neumann@s-direktnet.de)
#

module Text # :nodoc:
module Soundex

  def soundex(str_or_arr)
    case str_or_arr
    when String
      soundex_str(str_or_arr)
    when Array
      str_or_arr.collect{|ele| soundex_str(ele)}
    else
      nil
    end
  end
  module_function :soundex

  private

  #
  # returns nil if the value couldn't be calculated (empty-string, wrong-character)
  # do not change the parameter "str"
  #
  def soundex_str(str)
    return nil if str.empty?

    str = str.upcase
    last_code = get_code(str[0,1])
    soundex_code = str[0,1]

    for index in 1...(str.size) do
      return soundex_code if soundex_code.size == 4

      code = get_code(str[index,1])

      if code == "0" then
        last_code = nil
      elsif code == nil then
        return nil
      elsif code != last_code then
        soundex_code += code
        last_code = code
      end
    end # for

    return soundex_code + "000"[0,4-soundex_code.size]
  end
  module_function :soundex_str

  def get_code(char)
    char.tr! "AEIOUYWHBPFVCSKGJQXZDTLMNR", "00000000111122222222334556"
  end
  module_function :get_code

end # module Soundex
end # module Text

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
text-1.2.3 lib/text/soundex.rb
text-1.2.2 lib/text/soundex.rb
text-1.0.5 lib/text/soundex.rb
text-1.2.1 lib/text/soundex.rb
text-1.2.0 lib/text/soundex.rb
text-1.0.4 lib/text/soundex.rb
text-1.0.3 lib/text/soundex.rb
text-1.0.2 lib/text/soundex.rb
text-1.0.1 lib/text/soundex.rb
text-1.0.0 lib/text/soundex.rb
text-0.2.0 lib/text/soundex.rb