我正在编写一个小程序,它接受一个单词(或数组中的几个单词)和一个单词列表(“字典”)作为输入,并返回在该单词中找到输入单词的次数。字典。结果必须以哈希形式显示。
在我的代码中,我迭代输入的单词并查看字典 .include?
是否是该单词。然后,我将一个键/值对添加到我的哈希中,键是找到的单词,每次该单词出现在字典中时,值都会增加 1。
我在代码中看不到任何明显的问题,但我得到的结果只是一个空哈希。这个特定的示例应该返回类似
{"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
关于arrays - 在 Ruby 哈希中创建动态键名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58122420/