Do we use else with unless statement?
Yes, we can use unless
with else
. We are free to go wherever we like but some people have opinion that it's not a good habit to use else
with unless
. We need to avoid from this.
Unfortunately, unless statement supports only else construct not elsif or elseunless with in it.
unless true
puts "one"
elsif true
puts "two"
else
puts "three"
end
SyntaxError: compile error
syntax error, unexpected kELSIF, expecting kEND
This may also be the reason that it restrict us.
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