首页 > 解决方案 > 在 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"])

标签: arraysrubyhash

解决方案


您必须删除*方法定义中的 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

推荐阅读