1 # ==============================================================================
3 # ==============================================================================
5 # (C) Copyright 2004 by Tilo Sloboda <tools@unixgods.org>
7 # updated: Time-stamp: <Sat 18-Dec-2004 12:44:13 Tilo Sloboda>
10 # Freely available under the terms of the OpenSource "Artistic License"
11 # in combination with the Addendum A (below)
13 # In case you did not get a copy of the license along with the software,
14 # it is also available at: http://www.unixgods.org/~tilo/artistic-license.html
17 # THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU!
18 # SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
19 # REPAIR OR CORRECTION.
21 # IN NO EVENT WILL THE COPYRIGHT HOLDERS BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL,
22 # SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY
23 # TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
24 # INACCURATE OR USELESS OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
25 # TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF THE COPYRIGHT HOLDERS OR OTHER PARTY HAS BEEN
26 # ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
28 # ==============================================================================
30 # Homepage: http://www.unixgods.org/~tilo/Ruby/invert_hash.html
33 # Ruby's Hash.invert method leaves a lot to wish for.. it can't handle the
34 # common case that two or more hash entries point to the same value..
37 # h = {"ooh gott"=>3, "bla"=>3, "aua"=>3, "kotz"=>2, "blubb"=>9, "seier"=>3, "schigga"=>9}
39 # => {2=>"kotz", 3=>"seier", 9=>"schigga"}
41 # the above result IS SIMPLY WRONG!
44 # => {"kotz"=>2, "seier"=>3, "schigga"=>9}
46 # h.invert.invert == h
49 # Let's conclude that Ruby's built-in Hash.invert method is REALLY BROKEN!
52 # OK, let's try this new inverse method:
54 # require 'invert_hash'
57 # => {2=>"kotz", 3=>["seier", "aua", "bla", "ooh gott"], 9=>["schigga", "blubb"]}
60 # => {"ooh gott"=>3, "bla"=>3, "aua"=>3, "kotz"=>2, "blubb"=>9, "seier"=>3, "schigga"=>9}
62 # h.inverse.inverse == h
65 # Looks much better, doesn't it?
77 i[x] = [k,i[x]].flatten
84 i[v] = [k,i[v]].flatten
97 # if you want to permanently overload Ruby's original invert method, you may want to do this:
100 alias old_invert invert