setting ruby hash .default to a list

Posted by matpalm on Stack Overflow See other posts from Stack Overflow or by matpalm
Published on 2008-10-10T10:28:53Z Indexed on 2010/04/06 1:13 UTC
Read the original article Hit count: 375

Filed under:
|
|
|

i thought i understood what the default method does to a hash...

give a default value for a key if it doesn't exist

irb(main):001:0> a = {}
=> {}
irb(main):002:0> a.default = 4
=> 4
irb(main):003:0> a[8]
=> 4
irb(main):004:0> a[9] += 1
=> 5
irb(main):005:0> a
=> {9=>5}

all good.

but if i set the default to be a empty list, or empty hash, i dont understand it's behaviour at all....

irb(main):001:0> a = {}
=> {}
irb(main):002:0> a.default = []
=> []
irb(main):003:0> a[8] << 9
=> [9]                          # great!
irb(main):004:0> a
=> {}                           # ?! would have expected {8=>[9]}
irb(main):005:0> a[8]
=> [8]                          # awesome!
irb(main):006:0> a[9]
=> [9]                          # unawesome! shouldn't this be [] ??

i was hoping / expecting the same behaviour as if i had used the ||= operator...

irb(main):001:0> a = {}
=> {}
irb(main):002:0> a[8] ||= []
=> []
irb(main):003:0> a[8] << 9
=> [9]
irb(main):004:0> a
=> {8=>[9]}
irb(main):005:0> a[9]
=> nil

can anyone explain what is going on ???

© Stack Overflow or respective owner

Related posts about ruby

Related posts about hash