散列我嘗試以下紅寶石代碼,我認爲將字長的散列返回到與那些長度的話。相反,它是空的。紅寶石添加具有數組值
map = Hash.new(Array.new)
strings = ["abc","def","four","five"]
strings.each do |word|
map[word.length] << word
end
但是,如果我將它修改爲
map = Hash.new
strings = ["abc","def","four","five"]
strings.each do |word|
map[word.length] ||= []
map[word.length] << word
end
它的工作。
不第一個版本剛創建哈希值,其默認值是空數組?在這種情況下,我不明白爲什麼這兩個區塊會給出不同的值。
這是奇怪的。對於第一個例子,如果你執行'map = Hash.new {| h,k | h [k] = []}' – 2012-07-21 03:56:33