我想知道 counts 变量的作用是什么,即最后一个结束之前的那个?
# 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"])
最佳答案
任何 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"]
有人可能会在 1.9 中编写相同方法的另一种方式:
def count_frequency(word_list)
Hash.new(0).tap do |counts|
word_list.each{ |word| counts[word]+=1 }
end
end
虽然有些人考虑使用 tap
像这样是一种虐待。 :)
而且,为了好玩,这里有一个稍慢但纯功能的版本:
def count_frequency(word_list)
Hash[ word_list.group_by(&:to_s).map{ |word,array| [word,array.length] } ]
end
关于ruby - 计数的目的是什么? 7号线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8218632/