Rescue On One Line
Here’s a handy tip we learnt from a colleague at CLUG (although it is talked about in Chapter 22 of the Pickaxe Book, 2nd edition – we just missed it). If you’ve got a simple rescue clause then you can just use the rescue keyword as a modifier on your statement like so:
Integer("test") rescue puts("Exception!")
There are a couple things to keep in mind:
- You do not get an exception parameter as you would on a full fledged rescue block
- You can only rescue StandardError exceptions and it’s descendants.
However you can do some nifty stuff. For instance, given an array of string representations of both integers and floats you can convert the array into numbers of the correct class like so:
["1","1.5","2"].map{|i| Integer(i) rescue Float(i)}
which will give you a result of
[1, 1.5, 2]
Aimred is a specialist Ruby and Ruby on Rails development house and consultancy based in Cape Town, South Africa.