Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we use else with unless statement?

There exists an opinion about else statement that we should not use it with unless?

Can anybody explain why this is so, or are we free to do whatever we like?

like image 912
Waleed Arshad Avatar asked Jul 28 '16 05:07

Waleed Arshad


People also ask

What do you mean by unless statement?

Unless statement is used when we require to print false condition, we cannot use if statement and or operator to print false statements because if statement and or operator always works on true condition. Syntax: unless condition # code else # code end.

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

Ruby programmers (usually coming from other languages) tend to prefer the use if ! condition . On the other side, unless is widely use in case there is a single condition and if it sounds readable. Also see making sense with Ruby unless for further suggestions about unless coding style.

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.


1 Answers

You definitely can use else with unless. E.g.:

x=1 unless x>2    puts "x is 2 or less" else   puts "x is greater than 2" end 

Will print "x is 2 or less".

But just because you can do something doesn't mean you should. More often than not, these constructs are convoluted to read, and you'd be better served to phrase your condition in a positive way, using a simple if:

x=1 if x<=2    puts "x is 2 or less" else   puts "x is greater than 2" end 
like image 83
Mureinik Avatar answered Sep 18 '22 01:09

Mureinik