Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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?

like image 564
Goalie Avatar asked Apr 26 '12 18:04

Goalie


People also ask

Does Ruby have else if?

Ruby if...else Statement if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif. Executes code if the conditional is true.

What is the difference between if and unless statement in Ruby?

In if statement, the block executes once the given condition is true, however in unless statement, the block of code executes once the given condition is false.

What does &: mean in Ruby?

What you are seeing is the & operator applied to a :symbol . In a method argument list, the & operator takes its operand, converts it to a Proc object if it isn't already (by calling to_proc on it) and passes it to the method as if a block had been used.

How do you break out of if statements in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.


2 Answers

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 
like image 153
Sergio Tulentsev Avatar answered Sep 20 '22 04:09

Sergio Tulentsev


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.

like image 20
Charles Caldwell Avatar answered Sep 21 '22 04:09

Charles Caldwell