creating fallback for sad code
Contact me at LinkedIn  RailsZilla at Facebook  RailsZilla at twitter   google +1  Contact me at Xing  connect me at github

creating fallback for sad code

Posted in Rails

You can use rescue to create a fallback scenario, when your code gets strange…
Just return a value to rescue. Our example will show it as follows:

First we create a hash with a key/value pair and store it in h

h = { :age => 35 }

Now let’s bother our script with a method on a key we don’t have. We have no symbol in our hash called :name. This will return an ERROR


Still we have no key with a symbol called :name. Now we have a fallback given as a value to rescue. This will return “No name” instead of an ERROR

h[:name].downcase rescue "No name"

I’ve been kicked badly by using this too often. It catches a vast amount of exception types, so don’t exaggerate this ;-)

Tags: , , ,


Leave a Reply

Your email address will not be published. Required fields are marked *

Please enter a secure code to see if you are a spammer ;-)


Copyright © 2011-2018  - RailsZilla – Ruby on Rails tutorials, tips and tricks All rights reserved. | Imprint | Privacy