Goalie
Goalie

Reputation: 3105

Is there a shorthand if (without else) statement in Ruby on Rails?

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

Answers (2)

Charles Caldwell
Charles Caldwell

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

Sergio Tulentsev
Sergio Tulentsev

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

Related Questions