I recently learned that you can use rescue
on a line of code in case something goes wrong on that line (see http://www.rubyinside.com/21-ruby-tricks-902.html Tip #21). I have some code that used to look like this:
if obj['key'] && obj['key']['key2'] && obj['key']['key2']['name']
name = obj['key']['key2']['name']
else
name = ''
end
With the rescue
method, I believe I can change that code into something like this:
name = obj['key']['key2']['name'] rescue ''
If a nil exception is thrown at any level of accessing the hash, it should get caught by the rescue and give me '', which is what I want. I could also choose to set name to nil
if that were the desired behavior.
Is there any known danger in doing this? I ask because this seems too good to be true. I have so much ugly code that I'd love to get rid of that looks like the first code example.