From: Sam Roberts Date: 2004-01-28T02:25:30+09:00 Subject: Re: newbee question about "missing" hash methods +, += and << Quoteing hal9000@hypermetrics.com, on Wed, Jan 28, 2004 at 01:34:36AM +0900: > ts wrote: > > Array#+ always add elements, with Hash#+ keys will be added only if the > > key don't exist otherwise the old value is replaced. > > I have seen this discussion before. > > It doesn't bother me much that keys are replaced. That is the nature of > a Hash, that keys are unique. > > What bothers me more: If h2 and h3 have common keys, then > h1 = h2 + h3 > is not the same as > h1 = h3 + h2 > > In other words, I expect + to be commutative always. But probably > someone will now show me a case where it is not in Ruby. :) % irb irb(main):001:0> "a" + "b" => "ab" irb(main):002:0> "b" + "a" => "ba" irb(main):003:0> "b" * 3 => "bbb" irb(main):004:0> 3 * "b" TypeError: String can't be coerced into Fixnum from (irb):4:in `*' from (irb):4 I've heard this used as an argument that string classes in C++ should not have "+" - that it doesn't behave like addition should... (I know you're not among that group!). Those arguing this point lost, and now most people expect any reasonable implementation of a string object to respond to "+". On the other hand, it isn't as instantly obvious that you can lose data when you do "addition" on hashes, so maybe it protects us. Me, I vote it should be added as a standard method to Hash. It's useful to those who understand how it works, and it doesn't have any other obvious meaning. I.e., it would be hard for somebody to come back and say "that surprised me, I thought the "+" method would do ????". And for those who don't find it useful... don't use it! My 2 cents ($CA) ... Sam