We have an array of words here:
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
'flow', 'neon']
My teacher wrote a program that prints out groups of words that are anagrams. Anagrams are words that have the same exact letters in them but in a different order. The output should look something like this:
["demo", "dome", "mode"]
["neon", "none"]
(etc)
And here's the solution my 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 am bit confused how this program works such as when this part was set up result[key].push(word)
and the part where it says result[key] = [word]
I know this might be an off question a bit but can anyone one there can explain the solution line by line in a layman's term or in a way a dummy like me would understand.
PS. Sorry newbie here.