ruby - 计数的目的是什么? 7号线

标签 ruby return-value

我想知道 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/

相关文章:

ruby - 当其中一个操作数为 nil 时,按位或返回 bool 值

ruby - 在 Ruby (2.1+) 中调用父类(super class)初始值设定项时避免重复命名参数默认值

ruby - 返回 Enumerable 的 Ruby Enumerable.collect 的等价物?

java - 如何不仅返回正确的数据类型而且还返回数组?

ruby - 在 Mac 上定位 "irbrc"文件

ruby-on-rails - 将项目成对地分发到容器中 - Rails

objective-c - 在 C/Objective-C 中将返回值放在括号中的目的是什么?

C++ 静态构造函数返回一个容器

javascript - 修改此函数以显示所有选中的复选框的值(而不是最后选择的)

javascript - 如何从调用 $.getJSON 的函数返回值?