From: "Jesús Gabriel y Galán" Date: 2012-10-10T23:26:00+09:00 Subject: Re: Simulation of a dictionary On Wed, Oct 10, 2012 at 4:24 PM, Jesús Gabriel y Galán wrote: > On Tue, Oct 9, 2012 at 9:10 PM, Eric Christopherson > wrote: >> On Tue, Oct 9, 2012 at 1:17 PM, Joao Silva wrote: >>> Hi all. >>> >>> What I'm trying to do, is a program that has a hash with predefined >>> words and its corresponding meaning, then when I enter a word that is >>> found in the hash, I must return its meaning, and if not found in the >>> hash, should return the most similar word. >> >> Maybe use something like Levenshtein distance. >> >> Some links to look at: >> http://stackoverflow.com/questions/2158851/grouping-strings-by-similarity >> http://stackoverflow.com/questions/2531502/detect-similar-sounding-words-in-ruby >> > > The text gem has an implementation of the Levenshtein distance: > > require 'text' > > words={ > "computer" => "an electronic device ...", > "cat" => "a small domesticated carnivorous ...", > "home" => "the place where one lives permanently ...", > "dog" => "a domesticated carnivorous mammal ... " > } > > puts "Enter a word: " > s = gets.chomp > > if words.has_key?(s) > puts words[s] > else > distances = Hash.new {|h,k| h[k] = []} > words.keys.each {|word| distances[Text::Levenshtein.distance(word,s)] << word} > # puts "All words sorted by distance" > # distances.each {|distance, words| puts "#{distance} => #{words.join(",")} There's a typo in this line. Should be distances.each {|distance, words| puts "#{distance} => #{words.join(",")}"} > puts "nearest words: #{distances[distances.keys.sort.first]}" > end > > Jesus.