Do we use else with unless statement?

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

Leave a Comment