I am new to Ruby and I am trying to write a method that groups an array of words into anagram groups. Here is the code:
def combine_anagrams(words)
dict = words.inject(Hash.new(0)) do |list,ws|
key = sort_word(ws)
if !list.has_key?(key)
list[key] = []
end
list[key].push(ws)
list #What is this
end
return dict.values
end
My question is what the statement list is for. If I take it out list becomes an array instead of hash.
Every method/block/etc. in Ruby returns something, and unless there is an early
returnstatement, whatever the last statement in the method/block/etc. is, is what is returned.In your case, having
listbe the last line in the block passed toinjectensures thatlistis returned by the block. When you remove it, the return value oflist[key].push(ws)is returned, which obviously isn’t what you want.Note that this behavior also makes using the
returnkeyword when it is the last statement that would be executed otherwise is unnecessary (this includes thereturnyou have at the end of your method). Though some prefer to be explicit that they intend to return something and use them even when not needed.On an unrelated note: your
if !list.has_key?(key)can be rewrittenunless list.has_key?(key).