From: Robert Klemme Date: 2007-05-24T01:19:52+09:00 Subject: Re: Enumerator for Hash Wow! 5 identical postings in just two minutes. You must have been hitting "send" really hard... On 23.05.2007 18:00, Ryan Hinton wrote: > On May 23, 3:41 am, Robert Klemme wrote: > >> Make clear what you actually want. You could also show some code. > > Sorry for the confusion. I was trying to be considerate and brief, > but apparently I was only obscure. > > I want a Hash-like object that instead of calling each object's #hash > method to get its hash value, calls another to-be-specified method. I > probably want to specify an alternative to #eql? as well. Again, this > is parallel to the way the standard library Enumerator class creates > an Enumerable-like object with an alternative #each method. You could wrap your keys in a custom class. For added convenience you could also wrap Hash with another class which wraps keys on insertion and unwraps on reading. > One use cases is uniqueness. > > # existing array with a bunch of complex objects > my_array = [...] > > # find unique objects using normal #hash and #eql? methods; > # yes, I know Array#uniq does this -- it's an example > normal_uniq_hash = Hash.new > my_array.each {|obj| normal_uniq_hash[obj] = obj} > # now normal_uniq_hash can be iterated to get the unique objects from > my_array > > # find "unique" objects using different #hash and #eql? methods > alt_uniq_hash = AltHash.new(:alt_hash, :alt_eql?) # postulating a new > AltHash > my_array.each {|obj| alt_uniq_hash[obj] = obj} > # now alt_uniq_hash can be iterated to get the "unique" objects from > my_array In that case I'd probably rather do this: my_array.inject({}) {|hs, obj| hs[obj.key] ||= obj; hs }.values For example - using a string's length as uniqueness criterion: irb(main):001:0> my_array = %w{foo bar dodo dida longword} => ["foo", "bar", "dodo", "dida", "longword"] irb(main):002:0> my_array.inject({}) {|hs, obj| hs[obj.size] ||= obj; hs }.values => ["longword", "foo", "dodo"] > Is this more clear? Yes. > Thanks for your help! You're welcome. And please be easy on the trigger. ;-) Kind regards robert