Operators in Ruby Language

Operators in Ruby Language

Operators are fundamental elements of any programming language, including Ruby. They enable you to perform oper

ations on variables, values, and objects, making your code more expressive and concise. Ruby provides a wide range of operators, each with its own specific functionality. In this post, we’ll explore some of the most commonly used operators in the Ruby programming language.

Arithmetic Operators

Ruby supports the standard arithmetic operators for basic mathematical operations:

  • Addition +
  • Subtraction -
  • Multiplication *
  • Division /
  • Modulus % (returns the remainder of a division)
  • Exponentiation **
a = 10
b = 3

sum = a + b          # 13
difference = a - b   # 7
product = a * b      # 30
quotient = a / b     # 3.3333
remainder = a % b    # 1
exponent = a**b      # 1000

Comparison Operators

These operators are used to compare two values and return a Boolean result:

  • Equal to ==
  • Not equal to !=
  • Greater than >
  • Less than <
  • Greater than or equal to >=
  • Less than or equal to <=
x = 5
y = 8

x == y  # false
x != y  # true
x > y   # false
x < y   # true
x >= y  # false
x <= y  # true

Logical Operators

Logical operators are used to perform logical operations and manipulate Boolean values:

  • Logical AND &&
  • Logical OR ||
  • Logical NOT !
is_sunny = true
is_warm = false

if is_sunny && is_warm
  puts "It's a great day!"
end

if is_sunny || is_warm
  puts "At least one condition is met."
end

if !is_sunny
  puts "It's not sunny today."
end

Assignment Operators

Ruby provides several assignment operators for assigning values to variables while performing an operation:

  • Assignment =
  • Addition assignment +=
  • Subtraction assignment -=
  • Multiplication assignment *=
  • Division assignment /=
  • Modulus assignment %=
count = 10
count += 5    # count is now 15
count -= 3    # count is now 12
count *= 2    # count is now 24
count /= 4    # count is now 6
count %= 5    # count is now 1

Concatenation Operator

The + operator can be used to concatenate strings in Ruby:

first_name = "John"
last_name = "Doe"

full_name = first_name + " " + last_name
puts full_name  # "John Doe"

Ternary Operator

The ternary operator is a concise way to write conditional expressions:

age = 18
status = age >= 18 ? "Adult" : "Minor"
puts status  # "Adult"

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading