From: Daniel Berger Date: 2003-04-25T08:20:08+09:00 Subject: Re: Hashes and Enumerable#each_with_index Ryan Pavlik wrote: > > OK, looking at the archives I know this was discussed a few years ago, > but there seems to be no real conclusion or improvement since then. > > The problem: Hash#each_with_index returns an index that is not usable > to address the hash. That is, given the following: > > h = Hash.new > h.each_with_index { > | o, i | > ... > } > > i is not defined such that h[i] == o, which is both misleading and > seemingly useless. (This behavior, as per the previous discussion, can > be achieved with h.to_a.each_with_index.) > > Would it not be more useful to adopt the definiton of > Enumerable#each_with_index where the index given is such that e[i] == o > for any given Enumerable? This operation seems most sensical, to me, when used with ordered hashes. Here's a patch for Gotoken's "pseudohash" package on the RAA: # add to pseudohash.rb (not heavily tested) def [](k) if k.kind_of?(Fixnum) key = order[k] return self.fetch(key) else return super end end def each_with_index rest = keys - order order.each{|k,v| yield(k,self[k],order.index(k)) if include?(k)} rest.each{|k,v| yield(k,self[k],order.index(k)) } end example: record = PseudoHash.new.with_order ['Alice', 'Bob', 'Charlee'] record['Charlee'] = 90 record['Alice'] = 91 record['Bob'] = 89 record.each_with_index{|k,v,i| puts "Key: #{k}" puts "Index: #{i}" puts "Using index: " + record[i].to_s puts "Using key: " + record[k].to_s puts "=" * 10 } Regards, Dan a = [74, 117, 115, 116, 32, 65, 110, 111, 116, 104, 101, 114, 32, 82] a.push(117,98, 121, 32, 72, 97, 99, 107, 101, 114) puts a.pack("C*")