Class: Phonetic::Metaphone
- 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.
Constant Summary collapse
- VOWELS =
'AEIOU'- FRONT_VOWELS =
'EIY'- VARSON =
'CSPTG'
Class Method Summary collapse
-
.encode_word(word, options = { size: 4 }) ⇒ Object
Encode word to its Metaphone code.
Methods inherited from Algorithm
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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/phonetic/metaphone.rb', line 18 def self.encode_word(word, = { size: 4 }) code_size = [: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 = '' for n in 0..(l - 1) break unless .size < code_size symb = w[n] if symb == 'C' || n == 0 || w[n - 1] != symb case when vowel?(symb) && n == 0 = symb when symb == 'B' += symb if n != l - 1 || w[n - 1] != 'M' when symb == 'C' if n == 0 || w[n - 1] != 'S' || !front_vowel?(w[n + 1]) if w[n + 1, 2] == 'IA' += 'X' elsif front_vowel?(w[n + 1]) += 'S' elsif n > 0 && w[n + 1] == 'H' && w[n - 1] == 'S' += 'K' elsif w[n + 1] == 'H' if n == 0 && !vowel?(w[n + 2]) += 'K' else += 'X' end else += 'K' end end when symb == 'D' if w[n + 1] == 'G' && front_vowel?(w[n + 2]) += 'J' else += 'T' end when symb == 'G' silent = (w[n + 1] == 'H' && !vowel?(w[n + 2])) if n > 0 && (w[n + 1] == 'N' || w[n + 1, 3] == 'NED') silent = true end if n > 0 && w[n - 1] == 'D' && front_vowel?(w[n + 1]) silent = true end hard = (n > 0 && w[n - 1] == 'G') unless silent if front_vowel?(w[n + 1]) && !hard += 'J' else += 'K' end end when symb == 'H' if !(n == l - 1 || (n > 0 && VARSON[w[n - 1]])) += 'H' if vowel?(w[n + 1]) end when symb =~ /[FJLMNR]/ += symb when symb == 'K' if n > 0 && w[n - 1] != 'C' += 'K' elsif n == 0 = 'K' end when symb == 'P' += w[n + 1] == 'H' ? 'F' : 'P' when symb == 'Q' += 'K' when symb == 'S' if w[n + 1, 2] =~ /I[OA]/ += 'X' elsif w[n + 1] == 'H' += 'X' else += 'S' end when symb == 'T' if w[n + 1, 2] =~ /I[OA]/ += 'X' elsif w[n + 1] == 'H' += '0' if n == 0 || w[n - 1] != 'T' else += 'T' if w[n + 1, 2] != 'CH' end when symb == 'V' += 'F' when symb =~ /[WY]/ += symb if vowel?(w[n + 1]) when symb == 'X' += 'KS' when symb == 'Z' += 'S' end end end end |