为什么这个Ruby哈希不是我认为的那样?

时间:2012-12-25 01:06:36

标签: ruby hashmap

我有这段代码:

$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"}

2 个答案:

答案 0 :(得分:5)

使用$ze[5][0] = xxx,您首先调用[]的getter $ze,然后调用[]=的setter $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"}

答案 1 :(得分: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"}}
相关问题