On Wed, Oct 10, 2012 at 4:24 PM, Jes=FAs Gabriel y Gal=E1n
<jgabrielygalan / gmail.com> wrote:
> On Tue, Oct 9, 2012 at 9:10 PM, Eric Christopherson
> <echristopherson / gmail.com> wrote:
>> On Tue, Oct 9, 2012 at 1:17 PM, Joao Silva <lists / ruby-forum.com> 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-similarit=
y
>> http://stackoverflow.com/questions/2531502/detect-similar-sounding-words=
-in-ruby
>>
>
> The text gem has an implementation of the Levenshtein distance:
>
> require 'text'
>
> words=3D{
> "computer" =3D> "an electronic device ...",
> "cat" =3D> "a small domesticated carnivorous ...",
> "home" =3D> "the place where one lives permanently ...",
> "dog" =3D> "a domesticated carnivorous mammal ... "
> }
>
> puts "Enter a word: "
> s =3D gets.chomp
>
> if words.has_key?(s)
>   puts words[s]
> else
>   distances =3D Hash.new {|h,k| h[k] =3D []}
>   words.keys.each {|word| distances[Text::Levenshtein.distance(word,s)] <=
< word}
>   # puts "All words sorted by distance"
>   # distances.each {|distance, words| puts "#{distance} =3D> #{words.join=
(",")}

There's a typo in this line. Should be

distances.each {|distance, words| puts "#{distance} =3D> #{words.join(",")}=
"}

>   puts "nearest words: #{distances[distances.keys.sort.first]}"
> end
>
> Jesus.