From: Dan Doel Date: 2003-12-03T12:22:14+09:00 Subject: Re: Rite, Block locals and Autovivification John Carter wrote: >In Ruby, it is not so easy, but clearly "a[b]" doesn't make sense if >a.kind_of? Array and !b.kind_of?( FixNum), so "Do What I Mean" says you >should autovivify a Hash if appropriate. > > But you don't know what enum is until the method is called, so is your autovivification code really going to look like: if enum[0].kind_of? FixNum hash = Array.new(0) else hash = Hash.new(0) end ? But you really need to test all the elements on enum, because it doesn't have to have all the same type of elements. Also, Hashes can take FixNums as indicies, so who's to say I didn't actually want a hash, especially since you were sorting using keys and values later, so if someone mistakenly passed in an Enumerable containing only FixNums, your code would break. >Likewise whether in Perl "$a{$b}++" or ruby "a[b]+=1" the element at a[b] >should be autovivified as 0. > >In the case of > a[b]*=c >the only thing that makes sense is if a[b] autovivified as 1 > > Why does only 1 make sense? It would also be fine to say that a[b] *= c p a[b] # => 0 is the proper interpretation, in that all FixNums autovivify to have an initial value of 0, rather than having a value after assignment of whatever was used. Really, all these autovivification decisions are arbitrary, and having variables autovivify depending on how they're used would likely require a lot of extra analysis. Isn't it more consistant to make things autovivify always as nil, in cases where that's required (like "bar = bar; p bar", apparently)? - Dan