jonhue jonhue - 3 years ago 50
Ruby Question

Ruby: Throwing undefined method error

Running a statement like this:

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


Ruby throws the error
undefined method 'email' for nil:NilClass
, but it should just return
nil
instead. What am I doing wrong here?

Does it occur because in some cases
user
||
organization
is
nil
?

Answer Source

In self.user.email, if self.user is nill, then you can't call email on it.

If you're using Ruby 2.3 or newer, you can use the safe navigation operator:

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

Note the || nil at the end is probably unneccesary.

If you don't want to introduce a dependency to Ruby 2.3 or newer, you could use Object#try from ActiveSupport (included with Rails):

self.user.try(:email) || self.organization.try(:email)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download