Ruby - Unary operators

1. Introduction

In Ruby, a unary operator is an operator that operates on a single operand. Unlike binary operators that require two operands, unary operators require only one. The most common unary operators in Ruby are the +, -, !, and ~ operators.

2. Program Steps

1. Initialize sample variables.

2. Apply and demonstrate the unary operators on the initialized variables.

3. Code Program

# Initialize a sample variable
number = 5
# Unary Plus - Doesn't change the value, more commonly used in context with numbers to clarify code
positive_number = +number
puts "Unary Plus: #{positive_number}"
# Unary Minus - Changes the sign of the number
negative_number = -number
puts "Unary Minus: #{negative_number}"
# Unary Not (!) - Boolean NOT operation. Negates the truth value.
is_false = !true
puts "Unary Not: #{is_false}"
# Unary Bitwise Complement (~) - Inverts all the bits in the number
bitwise_complement = ~number
puts "Unary Bitwise Complement: #{bitwise_complement}"

Output:

Unary Plus: 5
Unary Minus: -5
Unary Not: false
Unary Bitwise Complement: -6

Explanation:

1. The Unary Plus is primarily for clarity and doesn't change the value of the operand.

2. The Unary Minus changes the sign of the number.

3. The Unary Not (!) negates the boolean value, changing true to false and vice versa.

4. The Unary Bitwise Complement (~) operator flips all the bits of its operand. For example, the number 5, in binary, is 101, and its complement is 010, which is 2. But due to how two's complement representation works for negative numbers, the result is -6 in base 10.


Comments