From: jmichel@... (Jean Michel) Date: 2001-01-04T05:10:02+09:00 Subject: [ruby-talk:8589] Re: bug?? In article , Hugh Sasse Staff Elec Eng wrote: >On Thu, 4 Jan 2001, Jean Michel wrote: > Thank you very much for the explanation. But there are two things I don't completely understand yet (or do not like - they do not seem to me to follow the principle of least surprise, and they make perl idioms fail) about the behaviour: >> irb(main):015:0> a=Hash.new("") >> {} > >Creates the new hash, and a single object <""> to return when >an nonexistent element is accessed. > >> irb(main):016:0> a[1]<<"a" >> "a" > >Access a nonexistent element -> "" >append "a" to it : "" << "a" -> "a" > >> irb(main):017:0> a[1] >> "a" > >Access a non existenet element. Get the one object back, as >before, but you just modified it, so it is "a", not "" any more. > >> irb(main):018:0> a >> {} > >You still haven't defined any keys for the hash yet, so there >is nothing in it. The first thing I do not like is that a[1]<<"a" does not create the key. I would expect that any method which modifes the receiver creates the key. I guess here to define the key the only solution is a[1]<<="a" ? The second thing I do not like is that when creating a non-existent element, ruby does not do a "dup" to give a new copy of this element. This more or less destroys the usefulness of the perl idiom 'automagically create elements'. Indeed if you do irb(main):019:0> a=Hash.new("") {} irb(main):020:0> a[1]<<="a" "a" irb(main):021:0> a {1=>"a"} irb(main):022:0> a[2]<<="b" "ab" irb(main):023:0> a {1=>"ab", 2=>"ab"} while in perl you would get {1=>"a", 2=>"b"} Is there any way to get the perl behaviour? Best regards, Jean MICHEL