I'm searching for an elegant way to bring the following if
statement into one line:
if var1.nil?
log("some message")
return
end
I love the right hand if
statement where you can say
return if var1.nil?
In this case, I need two actions, but the following doesn't work:
log("some message") and return if var1.nil?
Is there a way to perform two actions (log message and return) with an if
at the right side in one line?
When you have a method like return
, break
, etc., you can do (assuming that you are not interested in the return value):
return log("some message") if var1.nil?
A naive general way is:
(log("some message"); return) if var1.nil?
But if you don't like the parentheses and semicolon, then, do this: If and
does not work, then that means the return value of the first expression is falsy, which means or
should work.
log("some message") or return if var1.nil?
In general, one or the other between and
and or
would work, depending on the evaluated value of the first expression.
Well, to not depend on boolean evaluations you can always do something like this:
(log('some message'); return) if var.nil?
But I personally find it much less readable than the multiline version
if var1.nil?
log('some message')
return
end
One problem with the modifier-if syntax is that you may not even notice it when the line is too long. Observe:
(log('Something really bad happened while you were doing that thing with our app and we are terribly sorry about that. We will tell our engineers to fix this. Have a good day'); return) if var.nil?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With