我正在编写一个小程序,该程序将一个单词(或一个数组中的几个单词)和一个单词列表(一个“字典”)作为输入,并返回在字典中找到输入单词的次数。结果必须显示在哈希中。
在我的代码中,我正在遍历输入的单词,并查看字典.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。] >
[当您使用splat(*)运算符时,params一词将采用您传递给该方法的所有参数,并将其转换为数组,