From: Gavin Sinclair Date: 2002-08-05T08:27:06+09:00 Subject: Re: Assoc Class (Hash Pairs) ----- Original Message ----- From: "Joel VanderWerf" > Gavin Sinclair wrote: > > Hashes don't have "elements". They map Objects to Objects. That is their > > interface; that is what they are. "Map" is an English-language term used in > > documentation to describe the function of a Hash. You can iterate over the > > "mappings", and you are given the Objects contained therein. > > > > Hashes are no more, and no less, object-oriented than Arrays. > > Hashes do have elements in one sense: > > h = {:a=>1, :b=>2} > h.entries # ==> [[:b, 2], [:a, 1]] So they have "entries". Any container requires you to "enter" things (preferably Objects). > Or in the sense that you get ordered pairs when you iterate: > > h.each { |k,v| ... } Of course you get ordered pairs when you iterate; that's what a "map" is. > The ordered pairs don't "remember" that they came from a hash, but then > neither do the array elements you get when you iterate over an array. That's right, you're asking for the information inside the container. When it's presented, it's independent of the container. > Syntax preferences aside, why isn't an ordered pair good enough to > represent an association between two objects? It's got just enough > information (a first and a second element), and it uses the most > efficient construct for the job. What more could you want? An ordered pair is indeed a fine object to use as an association between two elements. In fact, I'd probably prefer to say hash.each do |pair| # do something with pair.key and pair.value end than hash.each do |pair| # do something with pair[0] and pair[1] end I'm a bit uncomfortable swapping to arrays whenever you sort a hash, etc. But those concerns are trivial, because I can write (as you pointed out) hash.each do |key,value| # do something with key and value end So in short, I don't dispute that Associations, or OrderedPairs, as first-class objects would be meaningful, consistent and perhaps useful as an "element" for Hash. My comments about hashes not having elements are intended to demonstrate that we don't need to think of hash elements in order to use them to their full potential. Hashes have their interface; Assocs etc. are (almost entirely) an implementation issue. > [code snipped] --Gavin