From: "Peña, Botp" Date: 2007-01-18T17:24:02+09:00 Subject: Re: printing 2 dimensionl hash problem From: Krekna Mektek [mailto:krekna@gmail.com] : #---------------------------------------------------------- # @h.each do |key,value| # print key, " is ", value.each {|x| print x, " -- " }, "\n" # # The print is strange, becuase it looks like this now: # # 1 -- 2 -- 3 -- A is 123 # 4 -- 5 -- 6 -- B is 456 # # 1. How come the code block is executed first #---------------------------------------------------------- print expects to print a value of the expression (of course). so before prints does the writing, it has to get the value first. #---------------------------------------------------------- # 2. After that the key and value is printed, however, I don't see the print for the values here (except for the print in de the code block, which was executed already). #---------------------------------------------------------- "value.each {...} " is an expression that returns a value, in this case the array "value". that expression however will perform *first a {|x| print x, "---"} for every element x in array "value". eg, C:\temp\rubygems-0.9.1>cat test.rb h = {"A" => [1,2,3], "B" =>[4,5,6]} puts "sample 1" h.each do |key,value| print key, " is " value.each {|x| print x, " -- " } print "\n" end puts puts "sample 2" h.each do |key,value| puts "#{key} is #{value.join(' -- ')}" end C:\temp\rubygems-0.9.1>ruby test.rb sample 1 A is 1 -- 2 -- 3 -- B is 4 -- 5 -- 6 -- sample 2 A is 1 -- 2 -- 3 B is 4 -- 5 -- 6 hth. kind regards -botp