How do I write a complex multi-line if condition in Ruby? How do I write a complex multi-line if condition in Ruby? ruby ruby

How do I write a complex multi-line if condition in Ruby?


The short answer is the operator needs to be at the end of the line in order to tell Ruby to continue reading the next line as part of the statement, so this would work:

if ( (aa != nil && self.prop1 == aa.decrypt) ||   (bb != nil && self.prop2 == bb.decrypt) ) &&   (self.id.nil? || self.id != id)  return trueend

That being said, you can probably reduce the logic by throwing exceptions based on input values, and removing some redundant checks (I'm making some jumps here about what your variables will look like, but you get the idea.)

raise 'aa must support decrypt' unless aa.respond_to? :decryptraise 'bb must support decrypt' unless bb.respond_to? :decryptif prop1 == aa.decrypt || prop2 == bb.decrypt  if self.id != id    return true  endend


You need to escape whitespace with the backslash character, it's ugly but you need it if you want to split conditions to multiple lines. Either that or leave the boolean operator on the previous line. So either of these will work:

if ( (aa != nil && self.prop1 == aa.decrypt)\      || (bb != nil && self.prop2 == bb.decrypt)\    ) && (self.id.nil? || self.id != id)     return true  end

or:

if ( (aa != nil && self.prop1 == aa.decrypt) ||       (bb != nil && self.prop2 == bb.decrypt)) &&    (self.id.nil? || self.id != id)     return true  end

Personally I usually decide to put each or all conditions in a method that self documents what's being decided:

def everythings_cool?  ( (aa != nil && self.prop1 == aa.decrypt) ||           (bb != nil && self.prop2 == bb.decrypt)) &&        (self.id.nil? || self.id != id) end

then:

if everythings_cool?  # do stuff