Ruby Logo

Ruby Documentation

Ruby Programming Language

Ruby is a dynamic, object-oriented programming language focused on simplicity and productivity. It has elegant syntax that is natural to read and easy to write. Created by Yukihiro "Matz" Matsumoto in 1995, Ruby follows the principle of least surprise and developer happiness.

Installation & Setup

Ruby can be installed on all major operating systems. Here are the recommended methods:

# macOS (using Homebrew)
brew install ruby
# Ubuntu/Debian
sudo apt update && sudo apt install ruby-full
# Using RVM (Ruby Version Manager)
curl -L https://get.rvm.io | bash -s stable
rvm install ruby

Verify your installation:

ruby --version
# Should output something like: ruby 3.2.2 (2023-03-30)

Your First Ruby Program

Create your first Ruby program with the classic "Hello, World!" example:

# hello_world.rb
puts "Hello, World!"

Run the program:

ruby hello_world.rb
# Output: Hello, World!

Interactive Ruby (IRB)

IRB is Ruby's interactive shell that allows you to execute Ruby code in real-time. It's perfect for experimentation and testing small code snippets.

# Start IRB
irb
irb(main):001:0>
puts "Hello from IRB!"
Hello from IRB!
=> nil

Variables & Constants

Ruby has four types of variables: local, instance, class, and global variables, plus constants.

# Local variables (lowercase or _)
name = "Alice"
age = 30
_private_var = "hidden"
# Instance variables (@)
@email = "alice@example.com"
# Class variables (@@)
@@count = 0
# Global variables ($)
$global_setting = "production"
# Constants (UPPERCASE)
PI = 3.14159
MAX_SIZE = 100

Data Types

Ruby has several built-in data types. Everything in Ruby is an object, including basic data types.

# Numbers
integer = 42
float = 3.14
complex = Complex(3, 4)
rational = Rational(1, 3)
# Strings
single_quotes = 'Hello'
double_quotes = "Hello #{name}" # interpolation
# Booleans and Nil
is_true = true
is_false = false
nothing = nil
# Symbols
status = :active
role = :admin

Arrays

Arrays are ordered collections of objects. They can contain any mix of data types.

# Creating arrays
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, true, :symbol]
empty = []
# Array methods
numbers.push(6) # Add to end
numbers << 7 # Shorthand for push
numbers.pop # Remove from end
numbers.first # First element
numbers.last # Last element
numbers.length # Array size

Hashes

Hashes are collections of key-value pairs. They're similar to dictionaries in other languages.

# Creating hashes
person = {
"name" => "Alice",
"age" => 30,
"city" => "New York"
}
# Symbol keys (modern syntax)
person = {
name: "Alice",
age: 30,
city: "New York"
}
# Accessing values
puts person[:name] # "Alice"
person[:email] = "alice@example.com" # Add new key

Control Flow & Conditionals

Ruby provides several ways to control the flow of your program with conditionals and loops.

# If/elsif/else statements
age = 25
if age >= 18
puts "You are an adult"
elsif age >= 13
puts "You are a teenager"
else
puts "You are a child"
end
# Unless statement
unless user.nil?
puts "Welcome, #{user.name}!"
end
# Case/when statements
grade = 'B'
case grade
when 'A'
puts "Excellent!"
when 'B', 'C'
puts "Good job"
else
puts "Keep trying"
end

Loops & Iterators

Ruby provides several ways to iterate and loop through data.

# While loop
counter = 0
while counter < 5
puts counter
counter += 1
end
# Times iterator
5.times do |i|
puts "Iteration #{i}"
end
# Each iterator
[1, 2, 3].each do |num|
puts num * 2
end
# Map iterator (transform array)
squared = [1, 2, 3].map do |num|
num ** 2
end
# squared is now [1, 4, 9]

Methods & Functions

Methods are reusable blocks of code that perform specific tasks. Ruby methods are flexible and powerful.

# Basic method definition
def greet(name)
"Hello, #{name}!"
end
# Method with default parameters
def create_user(name, role = "user")
{ name: name, role: role }
end
# Variable arguments (*args)
def sum(*numbers)
numbers.reduce(0, :+)
end
# Keyword arguments (**kwargs)
def build_profile(name:, age:, city: "Unknown")
"#{name}, #{age} from #{city}"
end
# Calling methods
puts greet("Alice")
puts sum(1, 2, 3, 4)
puts build_profile(name: "Bob", age: 30)

Blocks, Procs & Lambdas

Blocks are anonymous functions that can be passed to methods. Procs and lambdas are objects that wrap blocks.

# Blocks with do...end
[1, 2, 3].each do |number|
puts number * 2
end
# Blocks with curly braces (single line)
[1, 2, 3].map { |n| n ** 2 }
# Method that uses yield
def with_greeting
puts "Hello!"
yield if block_given?
puts "Goodbye!"
end
# Using the method with a block
with_greeting { puts "How are you?" }
# Procs
square_proc = Proc.new { |x| x ** 2 }
[1, 2, 3].map(&square_proc)
# Lambdas
cube_lambda = lambda { |x| x ** 3 }
cube_lambda.call(3) # Returns 27

Classes & Objects

Ruby is a purely object-oriented language. Everything in Ruby is an object, and you can create your own classes.

# Basic class definition
class Person
def initialize(name, age)
@name = name # Instance variable
@age = age
end
def introduce
"Hi, I'm #{@name} and I'm #{@age} years old."
end
# Getter methods
def name
@name
end
# Setter methods
def age=(new_age)
@age = new_age if new_age > 0
end
end
# Using attr_accessor shortcuts
class Car
attr_accessor :make, :model # getter & setter
attr_reader :year # getter only
def initialize(make, model, year)
@make, @model, @year = make, model, year
end
end
# Creating and using objects
person = Person.new("Alice", 30)
puts person.introduce
person.age = 31
car = Car.new("Toyota", "Camry", 2023)
puts car.make

Inheritance & Super

Ruby supports single inheritance, allowing classes to inherit from other classes and extend their functionality.

# Parent class
class Animal
def initialize(name)
@name = name
end
def speak
"#{@name} makes a sound"
end
end
# Child class inheriting from Animal
class Dog < Animal
def initialize(name, breed)
super(name) # Call parent's initialize
@breed = breed
end
def speak
"#{@name} the #{@breed} barks: Woof!"
end
def fetch
"#{@name} fetches the ball!"
end
end
# Using inherited classes
dog = Dog.new("Buddy", "Golden Retriever")
puts dog.speak
puts dog.fetch

Modules & Mixins

Modules provide namespacing and mixins. They can contain methods and constants but cannot be instantiated.

# Basic module definition
module Greetings
def say_hello
"Hello from module!"
end
def say_goodbye
"Goodbye from module!"
end
end
# Include module (adds instance methods)
class Person
include Greetings
end
person = Person.new
puts person.say_hello
# Extend module (adds class methods)
class Robot
extend Greetings
end
puts Robot.say_hello
# Module constants
module Math
PI = 3.14159
E = 2.71828
end
puts Math::PI

Exception Handling

Ruby's exception handling allows you to gracefully handle errors and unexpected situations in your code.

# Basic begin/rescue/ensure
begin
# Risky code
result = 10 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
ensure
puts "This always runs"
end
# Raising custom exceptions
def validate_age(age)
raise ArgumentError, "Age must be positive" if age < 0
"Valid age: #{age}"
end
# Custom exception classes
class InvalidEmailError < StandardError
def initialize(email)
super("Invalid email format: #{email}")
end
end
# Retry mechanism
retries = 0
begin
# Network call that might fail
fetch_data
rescue NetworkError
retries += 1
retry if retries < 3
raise
end

File I/O & Data Processing

Ruby provides excellent support for file operations and data processing with built-in libraries.

# Reading files
content = File.read("example.txt")
# Line by line reading
File.foreach("example.txt") do |line|
puts line.chomp
end
# Writing files
File.write("output.txt", "Hello, World!")
# Append to file
File.open("log.txt", "a") do |file|
file.puts "New log entry"
end
# JSON processing
require 'json'
data = { name: "Alice", age: 30 }
json_string = data.to_json
parsed_data = JSON.parse(json_string)
# CSV processing
require 'csv'
CSV.foreach("data.csv", headers: true) do |row|
puts row["name"]
end

Regular Expressions

Ruby has built-in support for regular expressions, making pattern matching and text processing powerful and elegant.

# Basic pattern matching
text = "My email is alice@example.com"
email_pattern = /\w+@\w+\.\w+/
if text =~ email_pattern
puts "Email found!"
end
# Extracting matches
email = text[email_pattern]
puts email # "alice@example.com"
# Capturing groups
phone_pattern = /(\d{3})-(\d{3})-(\d{4})/
phone = "555-123-4567"
if match = phone.match(phone_pattern)
puts "Area code: #{match[1]}"
puts "Number: #{match[2]}-#{match[3]}"
end
# String substitution
text.gsub(/\d+/, "XXX") # Replace all numbers
text.gsub(email_pattern, "[REDACTED]") # Hide email

Testing with Minitest & RSpec

Ruby has excellent testing frameworks. Minitest comes with Ruby, while RSpec is a popular alternative with BDD-style syntax.

# Minitest example
require 'minitest/autorun'
class CalculatorTest < Minitest::Test
def test_addition
calculator = Calculator.new
assert_equal 4, calculator.add(2, 2)
end
def test_division_by_zero
calculator = Calculator.new
assert_raises ZeroDivisionError do
calculator.divide(10, 0)
end
end
end
# RSpec example (BDD style)
require 'rspec'
describe Calculator do
let(:calculator) { Calculator.new }
describe '#add' do
it 'returns the sum of two numbers' do
expect(calculator.add(2, 3)).to eq(5)
end
end
end

RubyGems & Bundler

Ruby's package management system allows you to easily install, manage, and create reusable code libraries.

# Installing gems
gem install rails
gem install rspec
gem install pry
# Using Bundler (Gemfile)
source 'https://rubygems.org'
gem 'rails', '~> 7.0'
gem 'pg', '~> 1.0'
gem 'puma', '~> 5.0'
group :development, :test do
gem 'rspec-rails'
gem 'pry'
end
# Bundle commands
bundle install # Install dependencies
bundle exec rspec # Run with correct gem versions
bundle update # Update gems

Advanced Ruby Topics

Once you've mastered the fundamentals, explore these advanced Ruby concepts to become a Ruby expert:

🔮 Metaprogramming

  • Reflection & introspection
  • eval, instance_eval, class_eval
  • define_method & method_missing
  • Building DSLs
  • Hooks and callbacks

⚡ Concurrency

  • Threads & Thread pools
  • Fibers & Enumerators
  • Mutex & synchronization
  • Async/await patterns
  • Ractor (Ruby 3.0+)

🚀 Performance

  • Profiling & benchmarking
  • Memory optimization
  • Garbage collection tuning
  • JIT compilation
  • C extensions

🔧 Ruby Internals

  • YARV virtual machine
  • Object model & method lookup
  • Eigenclass (singleton class)
  • Module prepend & include
  • Ruby source code diving

🎯 Next Steps

Ready to level up your Ruby skills? Here's your roadmap to Ruby mastery:

  1. Practice the fundamentals - Build small programs using core concepts
  2. Learn Rails framework - Ruby's most popular web application framework
  3. Explore testing - Master RSpec, Minitest, and TDD/BDD practices
  4. Study popular gems - Understand how real-world Ruby libraries work
  5. Contribute to open source - Join the Ruby community and give back
  6. Build real projects - Create web apps, CLI tools, or gems

📚 Essential Resources

Official Documentation

  • ruby-lang.org/documentation
  • Ruby API Documentation
  • RubyGems.org

Books & Guides

  • The Ruby Programming Language
  • Effective Ruby
  • Ruby Metaprogramming

Community

  • Ruby Community Slack
  • GitHub Ruby Projects
  • Local Ruby Meetups

🎥 Video Tutorial

Watch comprehensive video explanations of key concepts