From: Mauricio Fernandez Date: 2007-01-08T23:44:19+09:00 Subject: Re: a most undangerous Hash#store! On Mon, Jan 08, 2007 at 09:37:05PM +0900, dblack@wobblini.net wrote: > On Mon, 8 Jan 2007, Mauricio Fernandez wrote: > >On Mon, Jan 08, 2007 at 08:20:05PM +0900, Robert Klemme wrote: > >>But only if you need the return value: > >> > >>irb(main):001:0> hash={:key=>1} > >>=> {:key=>1} > >>irb(main):002:0> hash.merge( :key => "new value" ) > >>=> {:key=>"new value"} > >>irb(main):003:0> hash > >>=> {:key=>1} > >> > >>The hash is merged properly. > > > >The original hash is not modified by #merge. > >#merge != #merge! (== #update) > > > >a = {} > >a.merge(:foo => 1) # => {:foo=>1} > >a # => {} > > Yes, merge was just a wrong turn on my part. Forget it. To be fair, the reference to #merge was not entirely misguided, since a = {:bar => 1, :foo => 2} {:foo => 0}.merge(a) # => {:bar=>1, :foo=>2} {:baz => 0}.merge(a) # => {:baz=>0, :bar=>1, :foo=>2} It just happens to work the other way around (cf. #reverse_merge mentioned earlier in this thread). Anyway, Trans was talking about destructive updates, so what about def store?(key, value) unless key?(key) store(key,value) return true end false end similar to the #store! he described, but with a more regular behavior when you have nil/false values... -- Mauricio Fernandez - http://eigenclass.org - singular Ruby