Reputation: 3105
I know there is a shorthand one-line if/else statement in Ruby:
a ? b : c
Is there one for just a single if
statement? Instead of writing this:
if a
# do something
end
Is there a shorthand version of this?
Upvotes: 43
Views: 52200
Reputation: 17149
do_something if a
This will first evaluate the if
condition (in this case a
) and if it is true
(or in the case of a
, not false
or nil
) it will execute do_something
. If it is false
(or nil
) it will move on to the next line of code never running do_something
.
Upvotes: 7
Reputation: 230296
You can use post conditions (don't mind the name, it will be evaluated before the code. And do_something
will only be executed if condition evaluates to truthy value (i.e. not nil
or false
)).
do_something if a
Upvotes: 82