From: Robert Klemme Date: 2004-01-28T01:44:55+09:00 Subject: Re: newbee question about "missing" hash methods +, += and << "benny" schrieb im Newsbeitrag news:20040127171647.756933c0@bava.ho... > Hi, > > I'm wondering if there is a special reason for the class Hash not to have the methods +, += and << > just like Array. First of all, no class has a method "+=". Instead this is a syntactic shortcut that transforms "a += b" into "a = a + b" - whatever 'a' and 'b' are. > I would find it intuitive if I could do something like this > > testhash = Hash.new > testhash << {"some key" => "some value"} There is "update": irb(main):004:0> testhash = {} => {} irb(main):005:0> testhash.update( {"some key" => "some value"} ) => {"some key"=>"some value"} irb(main):006:0> testhash => {"some key"=>"some value"} > secondhash = {"some other key" => "some other value"} > testhash += secondhash > #-> {"some key" => "some value", "some other key" => "some other value"} irb(main):007:0> secondhash = {"some other key" => "some other value"} => {"some other key"=>"some other value"} irb(main):008:0> testhash.update secondhash => {"some other key"=>"some other value", "some key"=>"some value"} > thats the behaviour of arrays and I know that I could extend the class Hash, so that its supported. > I simply want to know if there is a special reason why it is not supported by default. I guess it's that Hash#update is peculiar because it depends on which hash is updated by the other, which is important if both Hashes share some keys. Apart from that Hash#+ might be a bit inefficient in situations where you want to update a Hash via +=. class Hash def +(h) dup.update(h) end end a = {} b = {} a += b # in reality: # tmp = a + b # a = tmp # old a is dropped Kind regards robert