How to use the "not" keyword in Ruby?

RubyServer Side ProgrammingProgramming

In Ruby, we use the not keyword when we want to get an expression and then invert its Boolean value. In simple words, if an expression evaluates to True, then by using the not keyword, we will get False as the result of the expression.

It can be said that the not keyword works like the "!" operator in Ruby, but the only difference between them is that the "!" operator has the highest precedence of all operators and the "not" operator has the lowest.


Here is the syntax of the not keyword in Ruby

not expression

Now, let's take a couple of examples and see how to use the not keyword in Ruby.

Example 1

Consider the code shown below.

first_variable = "ruby"

# Using not keyword
if not(first_variable == "ruby")
   puts "The variable does not match."
   puts "Learn How to Program in Ruby!"

In the above example, we declared a variable named "first_variable" and then we used the not keyword in combination with the if condition.


If we write the following code on any Ruby IDE, then we will get the following output in the terminal.

Learn How to Program in Ruby!

Example 2

Now let's take a slightly more complex code of the not operator in Ruby. Consider the code shown below.

variable_1 = "tutorialspoint"
variable_2 = "ruby_programming"
constant = 12345

# if with not keyword
if not(variable_1 == "tutorialspoint" &&
   variable_2 == "ruby_programming" &&
   constant == 12345)
      puts "Variables Don't Match. Please Check."
   puts "Hi, How Are You Doing?"


On execution, it will produce the following output.

Hi, How Are You Doing?

In the above code, we are using the not keyword in the if statement and also clubbing together multiple && statements to form an expression. Since the entire conditions of the && expression are True and then we flip the value using the not operator, that's why we get the above output.

Updated on 12-Apr-2022 08:39:24