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 counts were not at the end of the method, the return value would be the result of the for loop; in this case, that's the word_list array itself:
irb(main):001:0> def count(words)
irb(main):002:1> counts = Hash.new(0)
irb(main):003:1> for word in words
irb(main):004:2> counts[word] += 1
irb(main):005:2> end
irb(main):006:1> end
#=> nil
irb(main):007:0> count %w[ sparky the cat sat on the mat ]
#=> ["sparky", "the", "cat", "sat", "on", "the", "mat"]
Another way someone might write the same method in 1.9:
def count_frequency(word_list)
Hash.new(0).tap do |counts|
word_list.each{ |word| counts[word]+=1 }
end
end
Though some people consider using tap like this to be an abuse. :)
And, for fun, here's a slightly-slower-but-purely-functional version:
def count_frequency(word_list)
Hash[ word_list.group_by(&:to_s).map{ |word,array| [word,array.length] } ]
end
Ruby doesn't require you to use the return statement to return a value in a method. The last line evaluated in the method will be returned if an explicit return statement is omitted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With