我正在尝试创建一个方法来计算它从字典中使用单词的次数,并作为哈希返回。这是我现在的代码:
def substrings(words, dictionary)
hash = {}
substrings.downcase!
dictionary.each do |substring|
words.each do |word|
if word.include? substring +=1
end
end
end
hash.to_s
end
dictionary = ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"]
words = "below"
substrings(words, dictionary)
我收到了这个错误:
wrong number of arguments (given 0, expected 2)
我正在寻找类似的东西:
=> {"below"=>1, "low"=>1}
我尝试了很多东西,但它从来没有给我那个哈希。我要么得到一个未定义的方法错误,要么:
=> ["below", ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"]]
答案 0 :(得分:1)
您的错误是由“substrings.downcase!”行引起的。这是对子串方法的递归调用,它接受两个参数,而您不提供任何参数。如果不是这种情况,您仍然会收到错误,这是由此代码的无限递归引起的堆栈溢出。
答案 1 :(得分:0)
这会产生预期的结果,但我会words
交换word
:
def substrings(word, dictionary)
word = word.downcase
dictionary.select { |entry| word.include?(entry.downcase) }
.group_by(&:itself)
.map { |k, v| [k, v.size] }.to_h
end
这导致:
>> dictionary = ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"]
>> word = 'below'
>> substrings(word, dictionary)
=> {"below"=>1, "low"=>1}
并计算多个单词的副本,虽然没有明确说明,但大概是你所追求的:
>> dictionary = ["below", "be", "below", "below", "low", "be", "pizza"]
>> word = 'below'
>> substrings(word, dictionary)
=> {"below"=>3, "be"=>2, "low"=>1}
答案 2 :(得分:0)
您可以使用#reduce
:
def substrings(sentence, dictionary)
sentence = sentence.downcase
dictionary.reduce(Hash.new(0)) do |counts,word|
counts[word] +=1 if sentence.include?(word.downcase)
counts
end
end
dictionary = ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"]
sentence = "below"
substrings(sentence, dictionary) #=> {"below"=>1, "low"=>1}
或#each
:
def substrings(sentence, dictionary)
sentence = sentence.downcase
counts = Hash.new(0) # Makes the default value `0` instead of `nil`
dictionary.each do |word|
if sentence.include?(word.downcase)
counts[word] += 1
end
end
counts
end
dictionary = ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"]
sentence = "below"
substrings(sentence, dictionary) #=> {"below"=>1, "low"=>1}