一个简单的姓名拼音匹配

姓名一般是由两三个汉字组成,选其顺序且连续的拼音缩略的组合就算匹配成功。

 1 # encoding: UTF-8
 2 
 3 require 'chinese_pinyin'
 4 @name = "成吉思汗"
 5 pinyins = Pinyin.t(@name).split
 6 
 7 # 把姓名生成对应的拼音数组
 8 array = []
 9 pinyins.each_with_index do |han, index|
10   array[index] = []
11   han.size.times {|num| array[index] << han[0..(num - 1)] }
12 end
13 
14 as = []
15 array.size.times do |x|
16   sub_array = []
17 
18   # 第一趟生成姓名拼音缩略的所有满足顺序且连续的组合
19   array.each_with_index do |ele, i|
20     ni = i + x
21     sub_array << array[i..ni] if array[ni]
22   end
23 
24   # 第二趟把每个组合各自归并
25   sub_array.each do |arr|
26     while arr.size > 1
27       sub_as = []
28       arr[0].each {|a1| arr[1].each {|a2| sub_as << ( a1 + a2 ) } }
29       arr[0..1] = [sub_as]
30     end
31     as << arr
32     puts arr.join(' ')
33   end
34 
35 end
36 
37 as.flatten.join(',')

Ruby标准库里的abbr.rb是排除两个英文单词的共同缩略,见http://ruby-doc.org/stdlib/libdoc/abbrev/rdoc/classes/Abbrev.html