Tag: autovivification

如何处理组合 + =在Ruby中自动生成哈希?

为了实现Ruby哈希的自动生成,可以使用以下类 class AutoHash self, :update_key => k) end end def []=(k, v) @update[@update_index] = self if @update and @update_index super end def few(n=0) Array.new(n) { AutoHash.new } end end 该类允许执行以下操作 a = AutoHash.new a[:a][:b] = 1 pa[:c] # => {} # key :c has not been created pa # => {:a=>{:b=>1}} # note, that it […]

如果hash 不存在,如何分配hash =’c’?

有什么比这简单的方法 if hash.key?(‘a’) hash[‘a’][‘b’] = ‘c’ else hash[‘a’] = {} hash[‘a’][‘b’] = ‘c’ end