Ruby | unless Statement and unless Modifier

Ruby provides a special statement which is referred as unless statement. This statement is executed when the given condition is false. It is opposite of if statement. 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.
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

Here else block is executed when the given condition is true.



Flow Chart:

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to illustrate unless statement 
  
# variable a
a = 1
  
# using unless statement
# here 1 is less than 4
unless a > 4
      
    # this will print as
    # condition is false
    puts "Welcome!"
  
else
    puts "Hello!"
      
end

chevron_right


Output:

Welcome!

unless Modifier: You can also use unless as a modifier to modify an expression. When you use unless as a modifier the left-hand side behaves as a then condition and right-hand side behaves as a test condition.

Syntax:

statement unless condition

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to illustrate 
# unless modifier 
  
# variable b
b = 0
  
# unless is behave as a modifier
# here 'b += 2 ' is the statement
# b.zero? is the condition
b += 2 unless b.zero?
    puts(b)

chevron_right


Output:

0


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.