Class: Phonetic::Metaphone

Inherits:
Algorithm show all
Defined in:
lib/phonetic/metaphone.rb

Overview

Metaphone is a phonetic algorithm, published by Lawrence Philips in 1990, for indexing words by their English pronunciation. This class implements this algorithm.

Examples:

Phonetic::Metaphone.encode('Accola') # => 'AKKL'
Phonetic::Metaphone.encode('Nikki') # => 'NK'
Phonetic::Metaphone.encode('Wright') #=> 'RT'

See Also:

Constant Summary collapse

VOWELS =
'AEIOU'
FRONT_VOWELS =
'EIY'
VARSON =
'CSPTG'

Class Method Summary collapse

Methods inherited from Algorithm

encode

Class Method Details

.encode_word(word, options = { size: 4 }) ⇒ Object

Encode word to its Metaphone code



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/phonetic/metaphone.rb', line 18

def self.encode_word(word, options = { size: 4 })
  code_size = options[:size] || 4
  w = word.upcase.gsub(/[^A-Z]/, '')
  return if w.empty?
  two = w[0, 2]
  w[0] = ''  if two =~ /PN|AE|KN|GN|WR/
  w[0] = 'S' if w[0] == 'X'
  w[1] = ''  if two == 'WH'
  l = w.size
  metaph = ''
  for n in 0..(l - 1)
    break unless metaph.size < code_size
    symb = w[n]
    next unless symb == 'C' || n == 0 || w[n - 1] != symb
    case
    when vowel?(symb) && n == 0
      metaph = symb
    when symb == 'B'
      metaph += symb if n != l - 1 || w[n - 1] != 'M'
    when symb == 'C'
      metaph += encode_c(w, n)
    when symb == 'D'
      metaph += encode_d(w, n)
    when symb == 'G'
      metaph += encode_g(w, n)
    when symb == 'H'
      metaph += encode_h(w, n)
    when symb =~ /[FJLMNR]/
      metaph += symb
    when symb == 'K'
      metaph += encode_k(w, n)
    when symb == 'P'
      metaph += w[n + 1] == 'H' ? 'F' : 'P'
    when symb == 'Q'
      metaph += 'K'
    when symb == 'S'
      metaph += encode_s(w, n)
    when symb == 'T'
      metaph += encode_t(w, n)
    when symb == 'V'
      metaph += 'F'
    when symb =~ /[WY]/
      metaph += symb if vowel?(w[n + 1])
    when symb == 'X'
      metaph += 'KS'
    when symb == 'Z'
      metaph += 'S'
    end
  end
  metaph
end