2012-12-25 14 views
5

Bu kodu vardır:Bu Ruby hash, neden olduğunu düşündüğüm şey değil?

$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] 

Ve bu çıktısı şöyledir:

{"test"=>{0=>"a", 1=>"b", 3=>"c"}, 5=>{0=>"one", 1=>"two"}} 
{0=>"one", 1=>"two"} 

:

{"test"=>{0=>"a", 1=>"b", 3=>"c"}} 
{0=>"one", 1=>"two"} 

Neden çıktı değil mi? $ze[5][0] = xxx ile

+7

küresel değişkenleri kullanmayın, bunlar çirkin! – Hauleth

cevap

5

öncelikle sonra ayarlayıcı $ze[5] ait []= çağırarak, alıcı $ze ait [] çağrıda bulunuyorlar. Bakınız Hash's API.

$ze anahtar içermiyorsa, Hash.new(2) ile başlattığınız varsayılan değerini döndürür.

$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' 

Sen $ze şey eklemeden değil ama onun varsayılan karma anahtar/değer çiftlerini ekliyoruz. Bu yüzden bunu da yapabilirsiniz. $ze[5] ile aynı sonucu alacaksınız.

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

Oh! Varsayılan karma değeri bile değiştirebileceğinizi anlayamadım. Teşekkürler. – 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 

Yürütme:

$ 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"}} 
İlgili konular