Measure the distance between two strings with Ruby?

后端 未结 6 1964
-上瘾入骨i
-上瘾入骨i 2020-11-29 08:18

Can I measure the distance between two strings with Ruby?

I.e.:

compare(\'Test\', \'est\') # Returns 1
compare(\'Test\', \'Tes\') #          


        
6条回答
  •  眼角桃花
    2020-11-29 08:58

    Much simpler, I'm a Ruby show-off at times...

    # Levenshtein distance, translated from wikipedia pseudocode by ross
    
    def lev s, t
      return t.size if s.empty?
      return s.size if t.empty?
      return [ (lev s.chop, t) + 1,
               (lev s, t.chop) + 1,
               (lev s.chop, t.chop) + (s[-1, 1] == t[-1, 1] ? 0 : 1)
           ].min
    end
    

提交回复
热议问题