[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    hash default value
From:       Emmanuel Touzery <emmanuel.touzery () wanadoo ! fr>
Date:       2003-08-12 13:27:50
[Download RAW message or body]

Hello,

    I'm bitten by a hash default value problem. I wanted to avoid the
myHash[a] = {} if !myHash[a]; myHash[a]["blue"] = 1
    pattern by using hash default values, but i get an unexpected (for 
me) result:

irb(main):001:0> myHash = {}
{}
irb(main):002:0> myHash["blue"]["red"] = 1
NameError: undefined method `[]=' for nil
        from (irb):2
irb(main):003:0> myOtherHash = Hash.new({})
{}
irb(main):004:0> myOtherHash["blue"]["red"] = 1
1
irb(main):005:0> p myOtherHash
{}
nil

i expected that myOtherHash would be {"blue"=>{"red"=>1}}

what am i missing here? is there a workaround to the ugly syntax i said 
i want to avoid? (you have the right to say "store your data in a decent 
manner")

emmanuel

PS: don't think it matters, but i'm running ruby 1.6.7 (2002-03-01) 
[i586-mswin32]



[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic