Ruby Cheat Sheet

Hello World:

        
puts "Hello, World!"
        
    

Variables:

        
# Declaring variables
age = nil
pi = 3.14159
name = "John Smith"

# Assigning values
age = 25

# Initializing variables
count = 0
is_true = true
        
    

Data Types:

        
# Basic data types
number = 10
floating_point = 3.14
boolean = true
text = "Hello"

# Array data type
array = [1, 2, 3, 4, 5]

# Hash data type
hash_data = { key1: value1, key2: value2 }
        
    

Operators:

        
# Arithmetic operators
sum = 5 + 3
difference = 10 - 4
division = 15 / 2
remainder = 15 % 2
product = 4 * 6

# Comparison operators
is_equal = (5 == 5)
is_greater = (10 > 5)
is_less_than_or_equal = (15 <= 20)

# Logical operators
logical_and = true && false
logical_or = true || false
logical_not = !true
        
    

Conditional Statements:

        
# If statement
if condition
    # Code to execute if the condition is true
else
    # Code to execute if the condition is false
end

# Case statement
day = 3
case day
when 1
    puts "Monday"
when 2
    puts "Tuesday"
when 3
    puts "Wednesday"
else
    puts "Invalid day"
end
        
    

Loops:

        
# While loop
while condition
    # Code to execute while the condition is true
end

# Until loop
until condition
    # Code to execute until the condition becomes true
end

# For loop
for i in 1..5
    puts i
end

# Each loop
array.each do |element|
    puts element
end
        
    

Methods:

        
# Method declaration
def method_name(parameters)
    # Code to execute
end

# Method with return value
def multiply(a, b)
    result = a * b
    return result
end

# Method call
method_name(arguments)
        
    

Classes:

        
# Class declaration
class MyClass
    def initialize(name)
        @name = name
    end

    def greet
        puts "Hello, #{@name}!"
    end
end

# Creating an instance
my_object = MyClass.new("John")

# Calling instance methods
my_object.greet