From: David Alan Black Date: 2002-02-25T11:22:16+09:00 Subject: Re: Hash.each block parameters Hi -- On Mon, 25 Feb 2002, Sean O'Dell wrote: > I ran into a problem where I should have called .each_key for a hash, but I > was calling .each and so I wrote it like this: > > myhash.each do | key | > end > > I couldn't get values out of the hash using the key during the block > iterations. nil was always returned. > > I studied my code awhile and realized I should be using each_key. Hash.each > provides TWO block parameters, not one like each_key (the key). I added the > second parameter and things were fine again. > > It did this very quietly, no error or anything...I just got nil values and > scratched my head until I figured it out. Is there a parameter to make Ruby > stricter towards this sort of thing? Ruby isn't doing anything it shouldn't :-) When you iterate through a Hash with #each, you get each pair. So your variable "key" is actually an two-element array: myhash = Hash[*%w{ one un two deux three trois }] myhash.each {|pair| puts "key: #{pair[0]}; value: #{pair[1]}" } => key: three; value: trois key: one; value: un key: two; value: deux Actually you could just capture the key by putting in a comma: myhash.each {|key,| ... } but in this case it's clearer to use each_key, or myhash.keys.each . David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav