Ruby: Throwing undefined method error -


running statement this:

self.user.email || self.organization.email || nil 

ruby throws error undefined method 'email' nil:nilclass, should return nil instead. doing wrong here?

does occur because in cases user || organization nil?

in self.user.email, if self.user nill, can't call email on it.

if you're using ruby 2.3 or newer, can use safe navigation operator:

self.user&.email || self.organization&.email 

note || nil @ end unneccesary.

if don't want introduce dependency ruby 2.3 or newer, use object#try activesupport (included rails):

self.user.try(:email) || self.organization.try(:email) 

Comments

Popular posts from this blog

Ansible warning on jinja2 braces on when -

Parsing a protocol message from Go by Java -

html - How to custom Bootstrap grid height? -