From: Rob Biedenharn Date: 2008-08-19T00:38:57+09:00 Subject: Re: Hash#each vs Hash#each_pair On Aug 18, 2008, at 9:56 AM, Patrick Doyle wrote: >> p "p hash : #{hash}" >> p "hash.each" >> hash.each do |e| #e is [key,value] >> p e >> end > I am just trying to understand why hash.each returns [key, value] > instead of value the way that array.each does: > #!/usr/bin/ruby > > hash = {1 => 'one', 2 => 'two', 3 => 'three'} > array = ['one', 'two', 'three'] > > p "p hash : #{hash}" > p "hash.each" > hash.each do |e| #e is [key,value] > p e > end > > p "p array : #{array}" > p "array.each" > array.each do |e| > p e > end > > The answer might be "because that's the way it's always been done, and > there's no way we're going to change it because a newbie asked for it > to be changed!". (The careful reader might notice that I haven't > asked for anything to be changed -- I'm simply trying to understand > the thinking that went into the decision to make Hash#each operate > differently than Array#each) > > In my case, I have some code in which a bunch of data has been > collected into an array, and I would like to modify my code such that > the collection of data is stored in a Hash instead of an Array object. > I had assumed that, since I used object.each everywhere that I > iterated through my data, it would be as simple as changing the code > where I stuff the values into the collection. Obviously, my > assumption proved incorrect. Which led me to the question, "Now, I > wonder why they did that?" So I've asked the question. > > --wpd > (It seems that my first response got swallowed by the web) An Array contains elements, a Hash contains key-value pairs. Doesn't that make sense that Hash#each returns the pairs? It seems that your mental picture of "values of the container" is at odds with Ruby (Matz). You could alias Array#each_value to be Array#each and then use each_value for both types. Perhaps if your motivation for changing from Array to Hash was eliminating duplication, you really want to use a Set -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com +1 513-295-4739 Skype: rob.biedenharn