I am wondering what purpose does the counts variable serve, the one right before the last end?
# Pick axe page 51, chapter 4
# Count frequency method
def count_frequency(word_list)
counts = Hash.new(0)
for word in word_list
counts[word] += 1
end
counts #what does this variable actually do?
end
puts count_frequency(["sparky", "the", "cat", "sat", "on", "the", "mat"])
The last expression in any Ruby method is the return value for that method. If
countswere not at the end of the method, the return value would be the result of theforloop; in this case, that’s theword_listarray itself:Another way someone might write the same method in 1.9:
Though some people consider using
taplike this to be an abuse. 🙂And, for fun, here’s a slightly-slower-but-purely-functional version: