Ruby rescue statement modifier
My copy of The Ruby Programming Language arrived today. I dived straight in to find a canonical justification for my superstition that rescue with no arguments only rescues StandardError and its descendants, not Exception and its descendants.
Along the way, I discovered that the rescue keyword can be used as a statement modifier. If the modified statement raises an exception, the argument to the rescue keyword is used as the value of the expression. For example:
# Instead of this if (@elephant.nil? or @elephant[:color] == "pink") puts "Weird elephant, dude" end # You can do this if (@elephant[:color] == "pink" rescue true) puts "Weird elephant, dude" end
At first glance, I’m not wild about it, but maybe it’ll end up growing on me, like Enumerable#inject. Either way, it’ll probably prove useful in other ways.
