Ruby
Updated: September 10, 2025Categories: Languages
Printed from:
Ruby Cheatsheet: A Comprehensive Guide
Language Overview
Ruby is a dynamic, object-oriented programming language designed for programmer happiness and productivity. Created by Yukihiro Matsumoto in 1995, Ruby emphasizes the principle of least astonishment (POLA) and follows the philosophy that programming should be fun and intuitive.
Key Characteristics:
- Everything is an object
- Dynamic typing
- Interpreted language
- Support for functional and meta-programming
- Garbage-collected
- Cross-platform compatibility
Basic Syntax
Hello World
Ruby
12345678910# Simple print statement
puts "Hello, World!"
# Method definition
def greet(name)
"Hello, #{name}!"
end
puts greet("Ruby Developer")
Comments
Ruby
1234# Single-line comment
=begin
Multiline comment
Can span multiple lines
=end
Data Types
Primitive Types
Ruby
123456789101112131415161718# Integer
age = 30
big_number = 1_000_000 # Underscores for readability
# Float
pi = 3.14159
# String
name = "Ruby"
interpolated = "Hello, #{name}!"
# Boolean
is_true = true
is_false = false
# Nil
nothing = nil
Collection Types
Ruby
1234567891011121314# Array
fruits = ["apple", "banana", "cherry"]
mixed_array = [1, "two", :three]
# Hash (Dictionary)
person = {
name: "Alice",
age: 30,
city: "New York"
}
# Symbol
status = :active
Variables and Constants
Ruby
12345678910111213141516# Local variable
local_var = 42
# Instance variable
@instance_var = "I belong to an instance"
# Class variable
@@class_var = "Shared across all instances"
# Global variable
$global_var = "Accessible everywhere"
# Constant
DAYS_IN_WEEK = 7
PI = 3.14159
Operators
Arithmetic Operators
Ruby
12345678910a = 10
b = 3
puts a + b # Addition: 13
puts a - b # Subtraction: 7
puts a * b # Multiplication: 30
puts a / b # Division: 3
puts a % b # Modulo: 1
puts a ** 2 # Exponentiation: 100
Comparison Operators
Ruby
12345678910a = 5
b = 10
puts a == b # Equal to: false
puts a != b # Not equal to: true
puts a < b # Less than: true
puts a > b # Greater than: false
puts a <= b # Less than or equal to: true
puts a >= b # Greater than or equal to: false
Logical Operators
Ruby
1234567true_value = true
false_value = false
puts true_value && false_value # Logical AND: false
puts true_value || false_value # Logical OR: true
puts !true_value # Logical NOT: false
Control Structures
Conditional Statements
Ruby
1234567891011121314151617181920212223242526# If-else
x = 10
if x > 5
puts "x is greater than 5"
elsif x == 5
puts "x is equal to 5"
else
puts "x is less than 5"
end
# Ternary operator
result = x > 5 ? "Greater" : "Less or Equal"
# Case statement
grade = 'B'
case grade
when 'A'
puts "Excellent!"
when 'B'
puts "Good job!"
when 'C'
puts "Satisfactory"
else
puts "Needs improvement"
end
Loops
Ruby
123456789101112131415161718192021222324# While loop
count = 0
while count < 5
puts count
count += 1
end
# For loop
(1..5).each do |num|
puts num
end
# Times loop
5.times do |i|
puts "Iteration #{i}"
end
# Loop control
10.times do |i|
break if i > 5
next if i.even?
puts i
end
Functions
Basic Functions
Ruby
123456789101112131415# Method definition
def greet(name = "World")
"Hello, #{name}!"
end
puts greet # "Hello, World!"
puts greet("Ruby") # "Hello, Ruby!"
# Multiple return values
def multiple_values
[1, 2, 3]
end
a, b, c = multiple_values
Lambda and Proc
Ruby
12345678# Lambda
multiply = ->(x, y) { x * y }
puts multiply.call(3, 4) # 12
# Proc
multiply_proc = Proc.new { |x, y| x * y }
puts multiply_proc.call(3, 4) # 12
Blocks
Ruby
123456789# Block with yield
def demonstrate_block
puts "Before yield"
yield if block_given?
puts "After yield"
end
demonstrate_block { puts "Inside block" }
Object-Oriented Programming
Classes and Objects
Ruby
12345678910111213141516171819class Person
# Accessor methods
attr_accessor :name, :age
# Constructor
def initialize(name, age)
@name = name
@age = age
end
# Instance method
def introduce
"Hi, I'm #{@name}, #{@age} years old"
end
end
person = Person.new("Alice", 30)
puts person.introduce
Inheritance
Ruby
12345678910111213class Employee < Person
attr_accessor :company
def initialize(name, age, company)
super(name, age)
@company = company
end
def work_info
"Works at #{@company}"
end
end
Modules and Mixins
Ruby
12345678910111213module Swimmable
def swim
"I can swim!"
end
end
class Fish
include Swimmable
end
fish = Fish.new
puts fish.swim # "I can swim!"
Error Handling
Ruby
12345678910111213141516begin
# Risky code
result = 10 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
ensure
puts "This always runs"
end
# Custom exception
class CustomError < StandardError; end
def raise_custom_error
raise CustomError, "Something went wrong"
end
File I/O
Ruby
12345678910111213# Writing to a file
File.open("example.txt", "w") do |file|
file.puts "Hello, File!"
end
# Reading from a file
File.read("example.txt")
# Appending to a file
File.open("example.txt", "a") do |file|
file.puts "Another line"
end
Common Libraries and Frameworks
Standard Library
DateandTimefor date manipulationJSONfor JSON parsingCSVfor CSV file handlingURIfor URI parsing
Popular Frameworks
- Ruby on Rails: Full-stack web framework
- Sinatra: Lightweight web framework
- Hanami: Modern web framework
- RSpec: Testing framework
- Sidekiq: Background job processing
Best Practices
Code Style
- Use snake_case for variables and method names
- Use CamelCase for class and module names
- Prefer
do...endfor multiline blocks - Keep methods small and focused
- Use meaningful variable and method names
Performance Tips
- Use
freezefor immutable strings - Prefer
eachoverforloops - Use
mapinstead ofcollect - Avoid creating unnecessary objects
Virtual Environments
- Use RVM or rbenv for Ruby version management
- Create gemsets to isolate project dependencies
Testing
Ruby
1234567# RSpec example
RSpec.describe Calculator do
it "adds two numbers" do
expect(Calculator.add(2, 3)).to eq(5)
end
end
Resources for Further Learning
- Official Ruby Documentation: https://www.ruby-lang.org/
- Ruby on Rails Guides: https://guides.rubyonrails.org/
- RubyGems: https://rubygems.org/
- Ruby Style Guide: https://github.com/rubocop/ruby-style-guide
Conclusion
Ruby's elegant syntax, powerful object-oriented features, and focus on developer happiness make it a joy to work with. Embrace its philosophy of least astonishment and enjoy writing clean, expressive code!
Continue Learning
Discover more cheatsheets to boost your productivity