From: 7stud -- Date: 2007-10-25T09:11:26+09:00 Subject: Re: .each do |foo, bar| what does bar do? Thufir wrote: > >>From my understanding of a hash, you can iterate through the keys only > and then find the corresponding bit of the hash. > Your understanding is incorrect. > > in the > first line, why are both "real" and "code" part of the interation? > Ok, let's get some preliminaries straight: arr = [1, 2] a, b = arr puts a,b --output:-- 1 2 That's a form of what's called 'parallel assignment' in ruby. The each() method for a hash sends an array consisting of a key/value pair to a block: h = {"a"=>1, "b"=>2} h.each do |arr| p arr end --output:-- ["a", 1] ["b", 2] The output shows that each() *assigns* an array to the parameter variable 'arr'. Earlier it was established that parallel assignment can be used with arrays. So that loop can also be written like this: h = {"a"=>1, "b"=>2} h.each do |key, val| print key, val puts end --output:-- a1 b2 As you can see from the output, ruby is perfectly happy to do parallel assignment when passing that array to the block. > Why would this fail: > > code_words.each do |real| > idea.gsub!( real, code ) > end > For the same reason the following program will fail: puts code > > wouldn't the corresponding code get looked up by during the loop? > How? In the first instance, you say that it's your understanding that when examining a hash with each(), each() will only produce the keys, but then you ask why 'code', which is a value, isn't looked up during the loop. So, what exactly is your understanding? > > how could the above be changed so that it would work? > code_words.each do |arr| idea.gsub!( arr[0], arr[1] ) end -- Posted via http://www.ruby-forum.com/.