Reputation: 14726
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?
Upvotes: 8
Views: 4314
Reputation: 1166
Depending on your version of Ruby, there is another way to achieve this that is (in my opinion) a little more readable. The yield_self
method that was introduced in Ruby 2.5 has an alias called then
as of Ruby 2.6. It is available on all descendents of Object
(just about everything, including nil
).
log("some message").then { return } if var1.nil?
Since the return
keyword will actually exit the current method or lambda context, you can place the return inside the block provided to then
. Alternatively, you can just return the result of then
since it returns the resolved block value.
return log("some message").then { nil } if var1.nil?
The latter example would also be good for an early exit when the context is another block.
some_vars.map do |var1|
next log("some message").then { nil } if var1.nil?
# do something with var1
end
Personally, I think the first example reads a bit better, but it's nice to have a little flexibility when you need it.
Upvotes: 2
Reputation: 230286
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?
Upvotes: 6
Reputation: 168081
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.
Upvotes: 11