Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-line `if` return statement with two actions

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?

like image 669
23tux Avatar asked Dec 08 '22 00:12

23tux


2 Answers

  1. 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?
    
  2. A naive general way is:

    (log("some message"); return) if var1.nil?
    
  3. 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.

like image 197
sawa Avatar answered Dec 23 '22 20:12

sawa


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?
like image 31
Sergio Tulentsev Avatar answered Dec 23 '22 20:12

Sergio Tulentsev