1

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.

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
  • Is `validate(x, y)` returning a `Boolean`? – Drenmi May 01 '15 at 12:37
  • Normally errors, like exceptions, halt the process. Is their a particular reason why you want to avoid that? For example when you run my_method, are you then checking afterwards whether an error object is returned before moving on? Otherwise instead of returning error, you can raise error –  May 01 '15 at 12:41

3 Answers3

2

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
spickermann
  • 100,941
  • 9
  • 101
  • 131
1

If validate returns error when the input is wrong and nil otherwise, then you can do:

def my_method(x, y)
  validate(x, y) or # do something else
end
sawa
  • 165,429
  • 45
  • 277
  • 381
0

Another way to write the same thing would be:

 def my_method(x, y)
    unless validate(x, y)
        # do something else
    end
  end

This will return the answer to validate if it returns anything.

ABrowne
  • 1,574
  • 1
  • 11
  • 21