如果hash ['a']不存在,如何分配hash ['a'] ['b'] ='c'? [英] How to assign hash['a']['b']= 'c' if hash['a'] doesn't exist?

查看:138
本文介绍了如果hash ['a']不存在,如何分配hash ['a'] ['b'] ='c'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有比

简单的方法

 如果hash.key?('a')
hash [' a'] ['b'] ='c'
else
hash ['a'] = {} $ b $ hash ['a'] ['b'] ='c'
end


解决方案

最简单的方法是用块参数构建你的Hash

  hash = Hash.new {| h,k | h [k] = {}} 
hash ['a'] ['b'] = 1
hash ['a'] ['c'] = 1
hash ['b '] ['c'] = 1
puts hash.inspect
#{a=> {b=> 1,c=> 1},b => {c=> 1}}

$ c> new 创建一个新的空Hash作为默认值。您不希望这样:

  hash = Hash.new({})

,因为它将为所有默认条目使用完全相同哈希。


$ b $另外,正如Phrogz所指出的那样,你可以使用 default_proc

  hash = Hash.new {| h,k | h [k] = Hash.new(& h.default_proc)} 

UPDATE :我想我应该对 Hash.new({})进行澄清。当你这样说:

  h = Hash.new({})

这就好像这样说:

  h = Hash.new 
h.default = {}

然后,当您访问 h h [:k] [:m] = y 赋值,它的行为就像您这样做:

  if(h.has_key?(:k))
h [:k] [:m] = y
else
h.default [:m] = y
end

然后,如果你 h [:k2] [:n] = z ,你最终将分配 h.default [:n] = ž。请注意, h 仍然表示 h.has_key?(:k)为false。



然而,当你这样说的时候:

  h = Hash.new(0)

一切都会好起来的,因为你永远不会修改 h [k] 在这里,你只能从 h (它将使用默认值,如果需要的话)读取一个值,或者给赋值一个新值。 h


Is there any way simpler than

if hash.key?('a')
  hash['a']['b'] = 'c' 
else  
  hash['a'] = {}
  hash['a']['b'] = 'c' 
end

解决方案

The easiest way is to construct your Hash with a block argument:

hash = Hash.new { |h, k| h[k] = { } }
hash['a']['b'] = 1
hash['a']['c'] = 1
hash['b']['c'] = 1
puts hash.inspect
# "{"a"=>{"b"=>1, "c"=>1}, "b"=>{"c"=>1}}"

This form for new creates a new empty Hash as the default value. You don't want this:

hash = Hash.new({ })

as that will use the exact same hash for all default entries.

Also, as Phrogz notes, you can make the auto-vivified hashes auto-vivify using default_proc:

hash = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }

UPDATE: I think I should clarify my warning against Hash.new({ }). When you say this:

h = Hash.new({ })

That's pretty much like saying this:

h = Hash.new
h.default = { }

And then, when you access h to assign something as h[:k][:m] = y, it behaves as though you did this:

if(h.has_key?(:k))
    h[:k][:m] = y
else
    h.default[:m] = y
end

And then, if you h[:k2][:n] = z, you'll end up assigning h.default[:n] = z. Note that h still says that h.has_key?(:k) is false.

However, when you say this:

h = Hash.new(0)

Everything will work out okay because you will never modified h[k] in place here, you'll only read a value from h (which will use the default if necessary) or assign a new value to h.

这篇关于如果hash ['a']不存在,如何分配hash ['a'] ['b'] ='c'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆