January 2024
Intermediate to advanced
718 pages
20h 15m
English
Although the exception mechanism of raise and rescue is great for abandoning execution when things go wrong, it’s sometimes nice to be able to jump out of some deeply nested construct during normal processing. This is where the rarely used catch and throw come in handy.
Here’s a trivial example. The following code reads a list of words one at a time and adds them to an array. When done, it prints the array in reverse order. But, if any of the lines in the file don’t contain a valid word, we want it to abandon the whole process.
| | word_list = File.open("wordlist") |
| | catch(:done) do |
| | result = [] |
| | while (line = word_list.gets) |
| | word = line.chomp |
| | throw :done unless /^\w+$/ ... |
Read now
Unlock full access