I am reading “The Ruby Programming Language” and wanted to try the example provided in the book (Chapter 6, Altering Control Flow, catch and throw) for using catch/throw to break out of nested loops:
for matrix in data do
catch :missing_data do
for row in matrix do
for value in row do
throw :missing_data unless value
puts value
end
end
end
end
I defined data as an array of three matrices:
data
=> [[[2, 3, 7], [8, 9, 10], [0, 1, 4]], [[“a”, “b”, “c”], [“d”, false, “e”], [“f”, “g”, nil]], [[“abc”, “def”], [“ghi”, “jkl”]]]
However when I try the code in IRB (version 1.9.3p327), I get an “unexpected $end, expecting keyword_end” error. I’ve tried playing around with the code and have discovered that it works if I remove the outmost (i.e. for) loop, but with the loop I get the error. To double check, I created a simpler loop:
for i in [1,2,3] do
catch :two do
if i==2 then throw :two end
end
end
Again, I get the same situation: error with the for loop, no error without the for loop (in fact, using IRB, I don’t get the chance to enter the last ‘end’, but get the error after entering the fourth line above).
Does anyone know why I am getting this error?
This appears to be build and/or environment-dependent (I lean towards environment):
rubyfrom command lineirbInside
irbdropping thedoin the outerfor, or using{}for thecatch, works: