Here we have an array of words:
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
'flow', 'neon']
My teacher wrote a program that prints groups of words that are anagrams. Anagrams are words that have the same exact letters in them, but in a different order. The result should look something like this:
["demo", "dome", "mode"]
["neon", "none"]
(etc)
And here is the solution that our teacher showed us:
result = {}
words.each do |word|
key = word.split('').sort.join
if result.has_key?(key)
result[key].push(word)
else
result[key] = [word]
end
end
result.each do |k, v|
puts "------"
p v
end
I got a little confused about how this program works, for example, when this part was set up result[key].push(word)and the part where it says result[key] = [word]I know that this can be a problem, but can someone explain this decision line by line in a non-specialized term or in some then a mannequin like me would understand.
PS. Sorry, newbie here.