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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With