2012-12-25 48 views
5

我有这样的代码:为什么不是这个Ruby哈希我认为它会是什么?

$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", 1=>"b", 3=>"c"}, 5=>{0=>"one", 1=>"two"}} 
{0=>"one", 1=>"two"} 

+7

不要使用全局变量,它们是丑陋! – Hauleth

回答

5

随着$ze[5][0] = xxx你第一次调用吸气剂$ze[],然后调用二传手$ze[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但你要添加键/值对到其默认哈希值。 这就是为什么你也可以这样做。你将得到与$ze[5]相同的结果。

puts $ze[:do_not_exist] 
# => {0=>"one", 1=>"two"} 
+0

哦!我没有意识到你甚至可以修改默认的散列。谢谢。 – Turnsole

1
h = Hash.new(2) 
print "h['a'] : "; p h['a'] 

$ze = Hash.new(Hash.new(2)) 
print '$ze[:do_not_exist] : '; p $ze[:do_not_exist] 
print '$ze[:do_not_exist][5] : '; p $ze[:do_not_exist][5] 

$ze = Hash.new{|hash, key| hash[key] = {}} 
$ze['test'] = {0=> 'a', 1=>'b', 3 => 'c'} 
$ze[5][0] = 'one' 
$ze[5][1] = "two" 
print '$ze : '; p $ze 

执行:

$ ruby -w t.rb 
h['a'] : 2 
$ze[:do_not_exist] : {} 
$ze[:do_not_exist][5] : 2 
$ze : {"test"=>{0=>"a", 1=>"b", 3=>"c"}, 5=>{0=>"one", 1=>"two"}} 
相关问题