Search code examples
rubyrefactoringguard-clause

Ruby: Return if method returns a non-nil value


Is there a better/cleaner way to do this in Ruby?

def my_method(x, y)
  return error if (error = validate(x, y))
  # do something else
end

I call #validate elsewhere, so to keep things DRY, I have it return the error message.


Solution

  • What is wrong with this more explicit and more readable version?

    def my_method(x, y)
      error = validate(x, y)
    
      if error
        error
      else
        # do something else
      end
    end
    

    IMO there is no benefit in writing the shortest possible code. You should always aim to write the most readable and understandable code.