为什么这个Ruby哈希不是我认为的那样?
发布时间:2020-12-17 03:22:29 所属栏目:百科 来源:网络整理
导读:我有这个代码: $ze = Hash.new( Hash.new(2) )$ze['test'] = {0= 'a',1='b',3 = 'c'}$ze[5][0] = 'one'$ze[5][1] = "two"puts $zeputs $ze[5] 这是输出: {"test"={0="a",1="b",3="c"}} {0="one",1="two"} 为什么不输出: {"test"={0="a",3="c"},5={0="one"
我有这个代码:
$ze = Hash.new( Hash.new(2) ) $ze['test'] = {0=> 'a',1=>'b',3 => 'c'} $ze[5][0] = 'one' $ze[5][1] = "two" puts $ze puts $ze[5] 这是输出: {"test"=>{0=>"a",1=>"b",3=>"c"}} {0=>"one",1=>"two"} 为什么不输出: {"test"=>{0=>"a",3=>"c"},5=>{0=>"one",1=>"two"}} {0=>"one",1=>"two"} ? 解决方法
使用$ze [5] [0] = xxx,你首先调用$ze的getter [],然后调用$ze的setter [] = [5].见
Hash’s API.
如果$ze不包含密钥,它将返回使用Hash.new(2)初始化的默认值. $ze[5][0] = 'one' # in detail $ze[5] # this key does not exist,# this will then return you default hash. default_hash[0] = 'one' $ze[5][1] = 'two' # the same here default_hash[1] = 'two' 您没有向$ze添加任何内容,但是您正在将键/值对添加到其默认哈希中. puts $ze[:do_not_exist] # => {0=>"one",1=>"two"} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |