Ruby Keywords

Reserved words that define Ruby's syntax and structure

🔑 What are Ruby Keywords?

Ruby keywords are reserved words with special meanings in the language. They cannot be used as variable, method, or class names. These keywords form the foundation of Ruby's syntax and control program flow.


# Keywords in action
if true
  puts "Keywords control program flow"
end
                                    

Output:

Keywords control program flow

Keyword Categories

🔀

Control Flow

Keywords that control program execution

if, else, elsif, unless
case, when, then
while, until, for
📦

Definition

Keywords for defining structures

class, module, def
begin, end
do
🔄

Loop Control

Keywords for managing loops

break, next, redo
retry, return
yield
🛡️

Exception Handling

Keywords for error management

rescue, ensure, raise
begin, end

🔹 Control Flow Keywords

Control flow keywords determine how your program executes. They allow you to make decisions, create loops, and handle different conditions. These are the most commonly used keywords in Ruby programming.

# if, elsif, else
age = 18
if age >= 18
  puts "Adult"
elsif age >= 13
  puts "Teenager"
else
  puts "Child"
end

# unless (opposite of if)
unless age < 18
  puts "Can vote"
end

# case, when
grade = 'B'
case grade
when 'A'
  puts "Excellent"
when 'B'
  puts "Good"
else
  puts "Keep trying"
end

Output:

Adult
Can vote
Good

🔹 Loop Keywords

Loop keywords help you repeat code blocks. Ruby provides several ways to create loops, each suited for different situations. Understanding these keywords is essential for writing efficient, repetitive operations.

# while loop
count = 0
while count < 3
  puts "Count: #{count}"
  count += 1
end

# until loop (opposite of while)
num = 0
until num > 2
  puts "Number: #{num}"
  num += 1
end

# for loop
for i in 1..3
  puts "Iteration: #{i}"
end

Output:

Count: 0
Count: 1
Count: 2
Number: 0
Number: 1
Number: 2
Iteration: 1
Iteration: 2
Iteration: 3

🔹 Definition Keywords

Definition keywords are used to create classes, modules, and methods. These keywords form the building blocks of object-oriented programming in Ruby, allowing you to organize and structure your code effectively.

# class keyword
class Person
  def initialize(name)
    @name = name
  end
  
  def greet
    puts "Hello, I'm #{@name}"
  end
end

person = Person.new("Alice")
person.greet

# module keyword
module Greeting
  def say_hi
    puts "Hi there!"
  end
end

class Friend
  include Greeting
end

friend = Friend.new
friend.say_hi

Output:

Hello, I'm Alice
Hi there!

🔹 Loop Control Keywords

Loop control keywords modify loop behavior. They let you skip iterations, exit loops early, or restart loops. These keywords give you fine-grained control over how your loops execute.

# break - exits the loop
5.times do |i|
  break if i == 3
  puts "Break example: #{i}"
end

# next - skips to next iteration
5.times do |i|
  next if i == 2
  puts "Next example: #{i}"
end

# return - exits method
def check_number(num)
  return "Too small" if num < 10
  return "Just right" if num == 10
  "Too big"
end

puts check_number(5)
puts check_number(10)

Output:

Break example: 0
Break example: 1
Break example: 2
Next example: 0
Next example: 1
Next example: 3
Next example: 4
Too small
Just right

🔹 Exception Handling Keywords

Exception handling keywords help manage errors gracefully. They prevent your program from crashing when unexpected situations occur. Using these keywords makes your code more robust and user-friendly.

# begin, rescue, ensure
begin
  result = 10 / 0
rescue ZeroDivisionError
  puts "Cannot divide by zero!"
ensure
  puts "This always runs"
end

# raise keyword
def check_age(age)
  raise "Age cannot be negative" if age < 0
  puts "Age is valid: #{age}"
end

begin
  check_age(25)
  check_age(-5)
rescue => e
  puts "Error: #{e.message}"
end

Output:

Cannot divide by zero!
This always runs
Age is valid: 25
Error: Age cannot be negative

🔹 Boolean and Special Keywords

Boolean keywords represent true and false values, while special keywords like nil, self, and super have unique purposes. These keywords are fundamental to Ruby's logic and object-oriented features.

# true, false, nil
is_active = true
is_deleted = false
middle_name = nil

puts "Active: #{is_active}"
puts "Deleted: #{is_deleted}"
puts "Middle name: #{middle_name.inspect}"

# self keyword
class Calculator
  def self.add(a, b)
    a + b
  end
end

puts Calculator.add(5, 3)

# and, or, not
x = 5
puts "Valid" if x > 0 and x < 10
puts "Out of range" if x < 0 or x > 100

Output:

Active: true
Deleted: false
Middle name: nil
8
Valid

🧠 Test Your Knowledge

Which keyword is used to define a class in Ruby?