From: Jean-Hugues ROBERT Date: 2004-06-13T16:56:13+09:00 Subject: Re: How to ducktype a Hash? At 20:23 12/06/2004 +0900, you wrote: >Sean O'Dell wrote: >> So, how do I positively identify when an object is a hash or at least behaves >> like a hash? > >Use the method #to_hash instead. All hash-like objects should be able to >give a hash-representation of themselves. > > Rene This makes a lot of sense to me. It seems to be symmetric to to_str() too, which is good. As a matter of fact, my rcr.rb has a to_hash() for Array: # Have Array.to_h() return an ArrayAsHash. # Please note that aa.to_h().to_a() == aa, which was the initial intend. class Array def to_h() h = ArrayAsHash.new() each_index do |ii| h[ii] = self[ii] end return h end end # What you get when converting an Array into a Hash, see Array##to_h() # It is a Hash with keys that are integer indexes (from 0 up to size of hash). class ArrayAsHash < Hash def to_a() super().sort_by { |(k,v)| k }.collect { |(k,v)| v } # ToDo: There must be a faster solution to do that. end end # Have Hash.to_a() return an HashAsArray instead of an Array. # Besides the class there are no other difference. class Hash alias ruby_to_a to_a unless defined? ruby_to_a # Returns an array of [key,value] pairs. # Please note that h.to_a().to_h() == h for most purposes. def to_a() HashAsArray.new().replace( ruby_to_a()) end # Returns self. Much like Array##to_a() does. def to_h() self end end Yours, JeanHuguesRobert ------------------------------------------------------------------------- Web: http://hdl.handle.net/1030.37/1.1 Phone: +33 (0) 4 92 27 74 17