arrays - 在 Ruby 哈希中创建动态键名?
问题描述
我正在编写一个小程序,它将一个单词(或数组中的几个单词)和一个单词列表(“字典”)作为输入,并返回在字典中找到输入单词的次数。结果必须显示在哈希中。
在我的代码中,我正在遍历输入的单词并查看字典是否.include?
是单词。然后,我将一个键/值对添加到我的哈希中,键是找到的单词,每当单词出现在字典中时,值就会增加一。
我在我的代码中看不到任何明显的问题,但我得到的只是一个空哈希。这个特定的例子应该返回类似
{"sit" => 3,
"below" => 1}
代码:
dictionary = ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit", "sit", "sit"]
def Dictionary dictionary, *words
word_count = Hash.new(0)
words.each{|word|
if dictionary.include?(word)
word_count[word] += 1
end
}
print word_count
end
Dictionary(dictionary, ["sit", "below"])
解决方案
您必须删除*
方法定义中的 splat 运算符 ( ):
def Dictionary(dictionary, words)
word_count = Hash.new(0)
words.each do |word|
word_count[word] += 1 if dictionary.include?(word)
end
print word_count
end
Dictionary(dictionary, ["sit", "below"])
# {"sit"=>1, "below"=>1}
原因是 Ruby 将words
参数包装在一个数组中,这使得它成为[["sit", "below"]]
,当你迭代它时,你得到的值["sit", "below"]
是唯一的元素,因此条件返回 false。
正如 NullUserException 所述,结果与预期不符。为此,您需要交换正在迭代的单词数组:
...
dictionary.each do |word|
word_count[word] += 1 if words.include?(word)
end
...
你也可以看看each_with_object
方法。它非常适合这种情况:
dictionary.each_with_object(Hash.new(0)) do |word, hash|
next unless words.include?(word)
hash[word] += 1
end
推荐阅读
- ehcache - 如果 LoaderWriter 失败,使 Ehcache 返回过期数据
- c# - 使用 UCMA 创建电话会议
- batch-file - 批处理脚本调用自己的名称而不是某种类型的文件?
- azure - 如何使用 Azure 流分析将本地 SQL Server 用作输出?
- javascript - 如何点击下载图片
- vue.js - 在不同的 url 上有重复的命名路由定义警告
- javascript - 如何阻止任何脚本影响元素?
- google-cloud-platform - 如何使用 gsutil 命令查找对象和谷歌云存储桶的剩余到期时间和日期?
- node.js - 本地 Node.js 回馈“请求未定义”,但在线节点网站运行良好
- r - 在 azure ML 中创建自定义模块时加载 CRAN3.1 下不支持的 R 包