使用哈希收集有关单词使用情况的统计信息 [英] Using a hash to collect statistics on word usage

查看:57
本文介绍了使用哈希收集有关单词使用情况的统计信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个空的哈希,想用单词频率填充它.如果哈希遇到一个新单词,它必须将该单词初始化为关键字.如果找到以前见过的单词,它只会增加该键的值.这段代码是否有重构版本?

I have an empty hash and want to populate it with word frequencies. If the hash encounters a new word, it must initiate that word as a key. If it finds a word it has seen before, it simply increments that key's value. Is there a refactored version of this code?

my_hash = {}
@huge_word_list.words.each do |word|
    my_hash[word] ? my_hash[word] += 1 : my_hash[word] = 1
end

推荐答案

这是我偏爱的简洁方式:

This would be my preferred way to do it, explicit and concise:

@huge_word_list.each_with_object(Hash.new(0)) { |word, h| h[word] += 1 }

这篇关于使用哈希收集有关单词使用情况的统计信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆