Ruby Cheatsheet
Quick reference for Ruby syntax and common patterns
📋 Ruby Quick Reference
This cheatsheet provides quick access to Ruby's most common syntax, methods, and patterns. Perfect for beginners learning Ruby or experienced developers who need a quick reminder. Bookmark this page for instant reference during coding.
# Quick Ruby example
puts "Hello, Ruby!"
name = "World"
puts "Hello, #{name}!"
Output:
Hello, Ruby! Hello, World!
Essential Categories
Variables & Types
Data storage and types
name = "Ruby"
age = 25
price = 19.99
Control Flow
Conditions and loops
if condition
# code
end
Collections
Arrays and hashes
arr = [1, 2, 3]
hash = {a: 1, b: 2}
Methods & Classes
Functions and objects
def method_name
# code
end
🔹 Variables and Data Types
Ruby has dynamic typing, meaning you don't declare variable types. Variables can hold different types of data including strings, numbers, booleans, and nil. Understanding data types is fundamental to Ruby programming.
# Variables (no declaration needed)
name = "Alice" # String
age = 25 # Integer
price = 19.99 # Float
is_active = true # Boolean
nothing = nil # Nil
# Constants (uppercase)
PI = 3.14159
MAX_SIZE = 100
# String operations
greeting = "Hello"
full = greeting + " World" # Concatenation
interpolated = "Hi #{name}" # Interpolation
# Type checking
puts name.class # String
puts age.class # Integer
puts is_active.class # TrueClass
# Type conversion
puts "123".to_i # String to Integer
puts 456.to_s # Integer to String
puts "3.14".to_f # String to Float
Output:
String Integer TrueClass 123 456 3.14
🔹 Control Flow
Control flow statements determine how your program executes. Ruby provides if/else for conditions, case for multiple options, and various loop constructs. These are essential for creating dynamic, responsive programs.
# If/elsif/else
age = 18
if age >= 18
puts "Adult"
elsif age >= 13
puts "Teen"
else
puts "Child"
end
# Unless (opposite of if)
unless age < 18
puts "Can vote"
end
# Ternary operator
status = age >= 18 ? "Adult" : "Minor"
puts status
# Case/when
grade = 'B'
result = case grade
when 'A' then "Excellent"
when 'B' then "Good"
when 'C' then "Average"
else "Try harder"
end
puts result
# Modifier if/unless
puts "Valid" if age > 0
puts "Invalid" unless age > 0
Output:
Adult Can vote Adult Good Valid
🔹 Loops and Iteration
Ruby offers multiple ways to loop through data. While traditional loops exist, Ruby developers prefer iterators like each, map, and select. These methods are more expressive and align with Ruby's philosophy of readable code.
# While loop
count = 0
while count < 3
puts "Count: #{count}"
count += 1
end
# Until loop
num = 0
until num > 2
puts "Num: #{num}"
num += 1
end
# For loop
for i in 1..3
puts "For: #{i}"
end
# Times iterator
3.times { |i| puts "Times: #{i}" }
# Each iterator
[1, 2, 3].each { |n| puts "Each: #{n}" }
# Loop with break
loop do
puts "Loop"
break
end
# Next (skip iteration)
5.times do |i|
next if i == 2
puts i
end
Output:
Count: 0 Count: 1 Count: 2 Num: 0 Num: 1 Num: 2 For: 1 For: 2 For: 3 Times: 0 Times: 1 Times: 2 Each: 1 Each: 2 Each: 3 Loop 0 1 3 4
🔹 Arrays
Arrays store ordered collections of objects. Ruby arrays are dynamic, can hold mixed types, and come with powerful built-in methods for manipulation, searching, and transformation. They're one of Ruby's most versatile data structures.
# Creating arrays
arr = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, true]
empty = []
# Accessing elements
puts arr[0] # First element
puts arr[-1] # Last element
puts arr[1..3].inspect # Range
# Adding elements
arr.push(6) # Add to end
arr << 7 # Add to end
arr.unshift(0) # Add to start
# Removing elements
arr.pop # Remove last
arr.shift # Remove first
# Common methods
puts arr.length
puts arr.include?(3)
puts arr.first
puts arr.last
puts arr.reverse.inspect
puts arr.sort.inspect
# Iteration
arr.each { |n| puts n }
squares = arr.map { |n| n ** 2 }
evens = arr.select { |n| n.even? }
Output:
1 5 [2, 3, 4] 7 true 0 6 [6, 5, 4, 3, 2, 1, 0] [0, 1, 2, 3, 4, 5, 6]
🔹 Hashes
Hashes store key-value pairs, similar to dictionaries in other languages. They're perfect for structured data and configuration. Ruby hashes are fast, flexible, and support both string and symbol keys.
# Creating hashes
person = { "name" => "Alice", "age" => 25 }
user = { name: "Bob", age: 30 } # Symbol keys
# Accessing values
puts person["name"]
puts user[:name]
puts user.fetch(:age)
# Adding/updating
user[:city] = "NYC"
user[:age] = 31
# Removing
user.delete(:city)
# Common methods
puts user.keys.inspect
puts user.values.inspect
puts user.has_key?(:name)
puts user.length
# Iteration
user.each do |key, value|
puts "#{key}: #{value}"
end
# Merging
extra = { job: "Developer" }
full = user.merge(extra)
puts full.inspect
Output:
Alice
Bob
30
[:name, :age]
["Bob", 31]
true
2
name: Bob
age: 31
{:name=>"Bob", :age=>31, :job=>"Developer"}
🔹 Methods
Methods are reusable blocks of code that perform specific tasks. Ruby methods are defined with def and can accept parameters, return values, and use default arguments. They're essential for organizing and structuring your code.
# Basic method
def greet
puts "Hello!"
end
greet
# Method with parameters
def greet_person(name)
puts "Hello, #{name}!"
end
greet_person("Alice")
# Method with default parameter
def greet_with_title(name, title = "Mr.")
puts "Hello, #{title} #{name}"
end
greet_with_title("Smith")
greet_with_title("Jones", "Dr.")
# Method with return value
def add(a, b)
a + b # Implicit return
end
puts add(5, 3)
# Explicit return
def subtract(a, b)
return a - b
end
puts subtract(10, 4)
# Keyword arguments
def create_user(name:, age:, city: "Unknown")
"#{name}, #{age}, #{city}"
end
puts create_user(name: "Bob", age: 25)
Output:
Hello! Hello, Alice! Hello, Mr. Smith Hello, Dr. Jones 8 6 Bob, 25, Unknown
🔹 Classes and Objects
Classes define blueprints for objects. Ruby is fully object-oriented, meaning everything is an object. Classes encapsulate data and behavior, supporting inheritance, instance variables, and methods for creating robust, reusable code.
# Basic class
class Person
def initialize(name, age)
@name = name
@age = age
end
def introduce
puts "I'm #{@name}, #{@age} years old"
end
def name
@name
end
def age
@age
end
end
person = Person.new("Alice", 25)
person.introduce
puts person.name
# Class with attr_accessor
class User
attr_accessor :name, :email
attr_reader :id
def initialize(id, name, email)
@id = id
@name = name
@email = email
end
end
user = User.new(1, "Bob", "[email protected]")
puts user.name
user.name = "Robert"
puts user.name
Output:
I'm Alice, 25 years old Alice Bob Robert
🔹 Common String Methods
Strings are one of the most used data types. Ruby provides extensive string manipulation methods for case conversion, searching, splitting, and transformation. These methods make text processing simple and intuitive.
text = "Hello World"
# Case conversion
puts text.upcase
puts text.downcase
puts text.capitalize
puts text.swapcase
# Information
puts text.length
puts text.include?("World")
puts text.start_with?("Hello")
puts text.end_with?("!")
# Manipulation
puts text.reverse
puts text.gsub("World", "Ruby")
puts " spaces ".strip
puts text.split(" ").inspect
# Repetition and multiplication
puts "Ha" * 3
puts "-" * 10
Output:
HELLO WORLD hello world Hello world hELLO wORLD 11 true true false dlroW olleH Hello Ruby spaces ["Hello", "World"] HaHaHa ----------