From: Tammo Freese Date: 2001-03-06T23:50:14+09:00 Subject: [ruby-talk:12139] Re: (long) Re: hash.invert loses data if equal values exist - is this the right behaviour? At 23:10 06.03.01 +0900, you wrote: >Tammo Freese writes: > >> By inverting a hash that has same values, I expected to see an Exception. >> Curious which it would be, I tested it and found a surprising result: >> >> D:\software>ruby -ve 'p [hash = Hash[1, 3, 2, 3], hash.invert]' >> ruby 1.6.2 (2000-12-18) [i386-cygwin] >> [{1=>3, 2=>3}, {3=>2}] >> >> No exception. Is this correct? > >Any reason why there should be an exception? > > h = { 1 => 2 } # => {1=>2} > h[1] = 3 # => 3 > h # => {1=>3} > >It isn't exceptional to overwrite a value in a hash with another. Yes, it isn't. But the problem here is that it is not easy to predict which hash value overrides the others, because it seems to depend on the value and not on the order of appending it to the hash. Can you tell me how to figure out the result of the following code easily without looking at variable a and without thinking about the hashing strategy? puts "First:" # a = {} a[7] = 100 a[10] = 100 a[12] = 100 p a.invert puts "Second:" a = {} a[11] = 100 a[27] = 100 a[41] = 100 p a.invert puts "Third: " a = {} a[1] = 100 a[5] = 100 a[14] = 100 p a.invert # Or is the morale that I should not invert hashes with equal values because the results are too difficult to predict? - Tammo Freese freese@acm.org