Let's say I have a User object that has an email property, and I need the last top last line of their email :
u = User.find(1) letter = u.email.upcase.last
If u or email nil in this chain, I get a NoMethodError: undefined method 'blah' for nil:Nilclass . I have to work on it in most cases, but sometimes nil gets what he doesn't need or is hard to maintain. One way would be detailed:
u = User.find(1) letter = nil if u && u.email letter = u.email.upcase.last end
But it becomes annoying and dangerous in view or in a long chain of a.bunch.of.properties.down.a.hierarchy . I read about the try method in Rails:
u = User.find(1) letter = u.try(:email).try(:upcase).try(:last)
It's less verbose, but I feel bad writing all these attempts. And as soon as I put try in the chain, I have to use them to the end. Is there a better way?
source share