【发布时间】:2013-01-03 12:51:51
【问题描述】:
我正在尝试创建一个值作为数组的哈希。我正在向这些数组中添加元素,但由于某种原因,哈希在运行后变为空。我不知道为什么。这是我的代码
def function(words)
hash = Hash.new([]) # default value of empty list
words.each do |word|
sorted = word.chars.sort.join # sort the string
hash[sorted] << word
## hash becomes empty here
end
return hash
end
puts function ['cars', 'for', 'potatoes', 'racs', 'four']
我是 Ruby 新手,我不知道为什么哈希会自行清空它。我在 Python 中用相同的逻辑编写了一个类似的算法,它工作得非常好。有什么建议吗?
【问题讨论】:
-
您的实际和预期结果是什么?
-
添加到键值的附加元素(列表)。
标签: ruby hash dictionary