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

RubyIf StatementConditionalConditional Statements

Ruby Problem Overview


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;
}

Ruby Solutions


Solution 1 - 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 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

Solution 2 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChloeView Question on Stackoverflow
Solution 1 - RubyKyle SmithView Answer on Stackoverflow
Solution 2 - RubyDiegoSalazarView Answer on Stackoverflow