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

Chloe picture Chloe · Jan 28, 2014 · Viewed 54.7k times · Source

How do I write this multi-line, complex condition if statement in Ruby?

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

I'm getting Syntax error; unexpected tOROP.

In Java, I could write

if (
     ( (aa != null && aa.prop1.equals(aa.decrypt()))
     || (bb != null && bb.prop2.equals(bb.decrypt()))
     )
     && (this.id != id)
   ) {

   return true;
}

Answer

Kyle Smith picture Kyle Smith · Jan 28, 2014

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 true
end

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? :decrypt
raise 'bb must support decrypt' unless bb.respond_to? :decrypt
if prop1 == aa.decrypt || prop2 == bb.decrypt
  if self.id != id
    return true
  end
end