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.
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.
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.
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
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.