我正在写一个TFIDF程序 - 所有这些都应该没问题,但是我有一个小的(或很大的)问题,哈希按预期工作。为什么我的哈希函数不符合预期?
为了让这短暂的,手头上的代码是:
#Word matrix is an array that contains hashes (obviously)
#i've done some stuff before this and these are working as expected
puts word_matrix[3][:yahoo] # => 2
puts word_matrix[100][:yahoo] # => 0
puts $total_words_hash[:yahoo] #=> 0
#Essentially, this block is taking a hash of all the words (values = 0) and trying
#to run through them adding the only the values of the other hash to the temporary
#and then setting the temp to the old hash position (so that there are 0 values
#and the values occurring in that document.. yet, it assigns the same values to
#ALL of the hashes of word_matrix[]
#now we run this block and everything breaks down for some reason..
for i in 0...word_matrix.size
tmp_complete_words_hash = $total_words_hash #all values should be zero...
word_matrix[i].each do |key,val| #for each key in the hash we do this..
tmp_complete_words_hash[key] = val
end
word_matrix[i] = tmp_complete_words_hash
end
puts word_matrix[3][:yahoo] # => 2
puts word_matrix[100][:yahoo] # => 2 -- THIS SHOULD BE 0 Still...
任何人都可以摆脱任何光线,为什么这是指派相同的值到阵列的所有散列值?这就好像tmp_complete_words_hash
每次都没有被重置。
就像一个参考:像'$ total_words_hash'这样的全局变量通常是错误的东西,在正确编写的代码中很少需要。在'... word_matrix.size'中为'i'使用'for'也不是惯用的Ruby。学习使用'each'和'map'来代替你的数组。 –