Ruby logo
Ruby Cheatsheet
25 of 25 code examples
.rb
Hello World
Basic Ruby program
Basics
puts "Hello, World!"
Variables
Variable declarations
Basics
name = "John"
age = 30
price = 19.99
is_active = true

# Constants
PI = 3.14159
MAX_USERS = 1000
Strings
String operations
Basics
text = "Hello World"

# Interpolation
name = "John"
greeting = "Hello #{name}"

# Methods
length = text.length
upper = text.upcase
lower = text.downcase
reverse = text.reverse
includes = text.include?("World")
Arrays
Array operations
Data Structures
fruits = ["apple", "banana", "orange"]
fruits << "grape"

# Access
first = fruits[0]
last = fruits[-1]

# Methods
length = fruits.length
sorted = fruits.sort
reversed = fruits.reverse
joined = fruits.join(", ")
Hashes
Key-value pairs
Data Structures
person = {
  name: "John",
  age: 30,
  city: "New York"
}

# Access
name = person[:name]
age = person[:age]

# Methods
keys = person.keys
values = person.values
has_key = person.key?(:name)
Control Flow
If, loops, case
Basics
# If statement
if age >= 18
  puts "Adult"
elsif age >= 13
  puts "Teen"
else
  puts "Child"
end

# Unless
unless age < 18
  puts "Can vote"
end

# Case
case grade
when "A"
  puts "Excellent"
when "B"
  puts "Good"
else
  puts "Needs improvement"
end
Loops
Different loop types
Basics
# Times loop
5.times { |i| puts i }

# Each loop
fruits.each { |fruit| puts fruit }

# While loop
i = 0
while i < 5
  puts i
  i += 1
end

# Until loop
i = 0
until i >= 5
  puts i
  i += 1
end
Methods
Function definitions
Functions
def greet(name)
  "Hello, #{name}!"
end

def add(a, b = 1)
  a + b
end

# Splat arguments
def sum(*numbers)
  numbers.sum
end

# Keyword arguments
def create_user(name:, age:)
  { name: name, age: age }
end
Classes
Class definitions
OOP
class Person
  attr_accessor :name, :age
  
  def initialize(name, age)
    @name = name
    @age = age
  end
  
  def introduce
    "Hello, I'm #{@name}"
  end
end

person = Person.new("Alice", 25)
puts person.introduce
Inheritance
Class inheritance
OOP
class Animal
  def speak
    "Some sound"
  end
end

class Dog < Animal
  def speak
    "Woof!"
  end
end

class Cat < Animal
  def speak
    "Meow!"
  end
end

dog = Dog.new
puts dog.speak
Modules
Mixins and namespaces
OOP
module Loggable
  def log(message)
    puts "LOG: #{message}"
  end
end

class User
  include Loggable
  
  def create
    log "User created"
  end
end

user = User.new
user.create
Blocks
Code blocks
Functions
# Basic block
[1, 2, 3].each do |number|
  puts number * 2
end

# Yield
def execute_block
  yield if block_given?
end

execute_block { puts "Block executed" }

# Proc
double = Proc.new { |x| x * 2 }
result = double.call(5)
Lambdas
Anonymous functions
Functions
# Lambda
double = ->(x) { x * 2 }
puts double.call(5)

# Multiple parameters
add = ->(a, b) { a + b }
puts add.call(3, 4)

# As argument
numbers = [1, 2, 3]
doubled = numbers.map(&->(x) { x * 2 })
Symbols
Immutable strings
Basics
# Symbols
:name
:email
:user_id

# Usage in hashes
person = {
  name: "John",
  age: 30
}

# Conversion
"hello".to_sym
:hello.to_s
Ranges
Range objects
Data Structures
# Numeric ranges
(1..10).each { |i| puts i }
(1...10).each { |i| puts i } # excludes 10

# Character ranges
('a'..'z').each { |c| puts c }

# Methods
range = 1..10
includes = range.include?(5)
min = range.min
max = range.max
Enumerable
Collection methods
Data Structures
numbers = [1, 2, 3, 4, 5]

# Common methods
sum = numbers.sum
max = numbers.max
min = numbers.min
any = numbers.any? { |n| n > 3 }
all = numbers.all? { |n| n > 0 }

# Transformations
doubled = numbers.map { |n| n * 2 }
evens = numbers.select { |n| n.even? }
odds = numbers.reject { |n| n.even? }
Error Handling
Exceptions
Error Handling
begin
  result = 10 / 0
rescue ZeroDivisionError => e
  puts "Cannot divide by zero: #{e.message}"
rescue => e
  puts "Error: #{e.message}"
ensure
  puts "This always runs"
end

# Custom exception
class ValidationError < StandardError
end

def validate_age(age)
  raise ValidationError, "Invalid age" if age < 0
end
File I/O
File operations
I/O
# Reading
content = File.read("file.txt")
lines = File.readlines("file.txt")

# Writing
File.write("output.txt", "Hello World")

# Appending
File.open("log.txt", "a") do |file|
  file.puts "New entry"
end

# File info
exists = File.exist?("file.txt")
size = File.size("file.txt")
Regular Expressions
Pattern matching
Advanced
text = "Hello World"

# Matching
match = text.match(/World/)
if match
  puts "Found: #{match[0]}"
end

# Replacement
new_text = text.gsub(/World/, "Ruby")

# Scanning
emails = text.scan(/w+@w+.w+/)

# Validation
is_email = "test@example.com" =~ /Aw+@w+.w+z/
String Methods
More string operations
Basics
text = "  Hello World  "

# Trimming
trimmed = text.strip
left = text.lstrip
right = text.rstrip

# Splitting
words = text.split
parts = text.split(" ")

# Checking
empty = text.empty?
starts = text.start_with?("Hello")
ends = text.end_with?("World")

# Formatting
formatted = "Name: %s, Age: %d" % ["John", 25]
Array Methods
More array operations
Data Structures
numbers = [1, 2, 3, 4, 5]

# Adding/removing
numbers.push(6)
numbers.pop
numbers.unshift(0)
numbers.shift

# Searching
index = numbers.index(3)
include = numbers.include?(3)
first = numbers.first
last = numbers.last

# Set operations
a = [1, 2, 3]
b = [3, 4, 5]
union = a | b
intersection = a & b
difference = a - b
Hash Methods
More hash operations
Data Structures
person = { name: "John", age: 30 }

# Adding/updating
person[:city] = "New York"
person[:age] = 31

# Removing
person.delete(:age)

# Iterating
person.each { |key, value| puts "#{key}: #{value}" }
person.each_key { |key| puts key }
person.each_value { |value| puts value }

# Transforming
keys = person.keys
values = person.values
inverted = person.invert
Dates & Times
Date manipulation
Utilities
require 'date'

# Current time
now = Time.now
today = Date.today

# Creating
time = Time.new(2024, 1, 15)
date = Date.new(2024, 1, 15)

# Formatting
formatted = now.strftime("%Y-%m-%d %H:%M:%S")

# Arithmetic
tomorrow = today + 1
next_week = today + 7

# Components
year = now.year
month = now.month
day = now.day
JSON
JSON handling
Data Formats
require 'json'

# Hash to JSON
data = { name: "John", age: 30 }
json = data.to_json

# JSON to hash
parsed = JSON.parse(json)

# File operations
File.write("data.json", json)
loaded = JSON.parse(File.read("data.json"))
Metaprogramming
Dynamic code
Advanced
# define_method
class Person
  ["name", "age", "city"].each do |attribute|
    define_method(attribute) do
      instance_variable_get("@#{attribute}")
    end
  end
end

# method_missing
class DynamicClass
  def method_missing(method_name, *args)
    if method_name.to_s.start_with?("find_by_")
      attribute = method_name.to_s.split("find_by_").last
      # Implementation here
    else
      super
    end
  end
end

# send
person = Person.new
person.send(:name=, "John")