Chuck Brotman wrote:
Thank you all for your quick and helpful responses! In retrospect, it seems obvious (ain't it always the way???) . I was able to get the for/in syntax to work prior to asking the question, butr I couldn't get it to work with "each" . I think I had the styntax wrong I used {} instead of do end, And I
Both, pairs of curly braces and "do ... end", are valid ways of working with 'each'. They mostly differ in precedence
must have screwed that up because I ened up in never-never-land runing on freeRIDE's irb. I don't know if it was my or freeride!?).
If you show us the code (and the error message), we could find out what went wrong.
FWIW I like this solution: best due to its succinctness and reradablility::
(1..3).each do |i|
(4..6).each do |j|
printf "%d, %d, %d\n", i, j, i*j
end
Note that this
(1..3).each{ |i|
(4..6).each{ |j|
printf "%d, %d, %d\n", i, j, i*j
}
}
is just as valid.
However, many (probably most) people prefer to use curly braces in one liners like this
(4..6).each{ |j| printf "%d, %d, %d\n", i, j, i*j }
and "do ... end" for blocks with more than one line (like the example above).
Happy Rubying
Stephan