Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What purpose does counts serve? Line 7

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"])
like image 249
jimmyc3po Avatar asked Dec 29 '25 15:12

jimmyc3po


2 Answers

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
like image 97
Phrogz Avatar answered Dec 31 '25 12:12

Phrogz


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.

like image 33
Teddy Avatar answered Dec 31 '25 12:12

Teddy