ruby on rails - variable assigned in conditional is used in same conditional, throws error -


i'm trying this:

if user = user.find_by(email: 'example@example.com') && !user.activated?     # end 

but error thrown saying "no method 'activated' nil:nilclass"

is there way me accomplish functionality without using nested conditional?

you can use control flow operator and on logical operator && so:

  if user = user.find_by(email: 'example@example.com') , !user.activated?     #   end 

example:

if = 12 && a.even?    "working" end  #=> undefined method `even?' nil:nilclass if b = 12 , b.even?    "working" end  #=> "working" 

this works because and has lower precedent assignment assignment occur prior second conditional check.

as long don't mind found = in conditional, should == warnings.

second option:

your other option explicit parentheses ie.

if = 12 && a.even?    "working" end  #=> undefined method `even?' nil:nilclass if (b = 12) && b.even?    "working" end  #=> "working" 

this works because parentheses () evaluated first before conditional evaluated assignment occur inside parens , evaluated part of conditional.

more on ruby operator precedence


Comments