关于ruby中的哈希的问题(当将数组哈希到某个键时)

时间:2015-10-06 14:47:09

标签: ruby

我编写了一个函数,它将相同字符(但不是相同的序列)的单词组成<script src="jquery.magnific-popup.js"></script> <script src="../jquery.magnific-popup.js"></script> <script src="js/jquery.magnific-popup.js"></script> <script src="..js/jquery.magnific-popup.js"></script> ,键是这些单词的字符排序字符串,例如hash[key]。< / p>

但是,我的代码中的第8行可能出错了,当我hash_list["arst"] => ["rats""tars""star"]时,我得到puts word_list

&#34; .txt&#34;文件由许多行组成,如:

{}

我的代码:

alean
allow
away
be
behavior
...
...

2 个答案:

答案 0 :(得分:3)

Hash#new与对象一起用作参数会将同一个对象作为默认值返回给任何不存在且不会将其值添加到哈希值的键:

with_obj = Hash.new([])
with_obj[:test]
# => [] 
with_obj[:test] << 1
# => [1]
with_obj
# => {} # The :test key was not setted
with_obj[:test2]
# => [1] # The array object was changed when we did with_obj[:test] << 1

但是您可以使用块初始化哈希,并使用您想要的值设置新密钥。以这种方式使用块将在每次调用时初始化一个新数组:

with_block = Hash.new { |hash, key| hash[key] = [] }
with_block[:test]
# => [] 
with_block[:test] << 1
# => [1] 
with_block
# => {:test=>[1]} # This time the key is setted
with_block[:test2]
# => [] # And any new key will use a new instance of array
with_block
# => {:test=>[1], :test2=>[]} 

答案 1 :(得分:1)

您需要将第8行修改为:

word_list[word_sort] ||= []
word_list.push(word)

只需读取访问尚未存在的哈希元素,就不会创建它。

您必须写信给它,即您需要在其上拨打[]=,而不仅仅是[]