重要的是什么目的?第7行

jim*_*3po 3 ruby return-value

我想知道计数变量的用途是什么,就在最后一个结束之前?

# 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"])
Run Code Online (Sandbox Code Playgroud)

Phr*_*ogz 8

任何Ruby方法中的最后一个表达式是该方法的返回值.如果counts不在方法的末尾,则返回值将是for循环的结果; 在这种情况下,这就是word_list数组本身:

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"]
Run Code Online (Sandbox Code Playgroud)

有人可能在1.9中编写相同方法的另一种方式:

def count_frequency(word_list)
  Hash.new(0).tap do |counts|
    word_list.each{ |word| counts[word]+=1 }
  end
end
Run Code Online (Sandbox Code Playgroud)

虽然有些人认为tap像这样使用是滥用.:)

而且,为了好玩,这里有一个稍慢但纯粹功能的版本:

def count_frequency(word_list)
  Hash[ word_list.group_by(&:to_s).map{ |word,array| [word,array.length] } ]
end
Run Code Online (Sandbox Code Playgroud)