问题描述
我有一个单词数组,我想得到一个哈希值,其中键是单词,值是单词计数.
I have array of words and I want to get a hash, where keys are words and values are word count.
还有比我更美的方法吗:
Is there any more beautiful way then my:
result = Hash.new(0)
words.each { |word| result[word] += 1 }
return result
推荐答案
您使用的命令式方法可能是 Ruby 中最快的实现.通过一些重构,你可以写一个单行代码:
The imperative approach you used is probably the fastest implementation in Ruby. With a bit of refactoring, you can write a one-liner:
wf = Hash.new(0).tap { |h| words.each { |word| h[word] += 1 } }
另一种使用 Enumerable#each_with_object
的命令式方法:
Another imperative approach using Enumerable#each_with_object
:
wf = words.each_with_object(Hash.new(0)) { |word, acc| acc[word] += 1 }
使用现有抽象的功能/不可变方法:
A functional/immutable approach using existing abstractions:
wf = words.group_by(&:itself).map { |w, ws| [w, ws.length] }.to_h
请注意,这在时间上仍然是O(n),但它遍历了集合 3 次,并在此过程中创建了两个中间对象.
Note that this is still O(n) in time, but it traverses the collection three times and creates two intermediate objects along the way.
最后:频率计数器/直方图是一种常见的抽象,你可以在一些库中找到,比如 Facets:Enumerable#frequency.
Finally: a frequency counter/histogram is a common abstraction that you'll find in some libraries like Facets: Enumerable#frequency.
require 'facets'
wf = words.frequency
这篇关于数组到哈希:字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!