تخطَّ إلى المحتوى

Ruby Cheat Sheet

Overview

Ruby is a dynamic, open-source programming language with a focus on simplicity and productivity. Created by Yukihiro “Matz” Matsumoto in 1995, Ruby follows the principle of least astonishment, aiming to make programming natural and enjoyable. Everything in Ruby is an object, including primitives like integers and booleans, and the language supports multiple paradigms including object-oriented, functional, and procedural programming.

Ruby is renowned for its elegant syntax that is natural to read and easy to write. It powers the Ruby on Rails web framework, numerous DevOps tools like Chef, Puppet, and Vagrant, and is widely used for scripting, automation, and rapid prototyping. The RubyGems ecosystem provides access to over 170,000 libraries, and the language continues to evolve with significant performance improvements in Ruby 3.x through YJIT (Yet another Just-In-Time compiler).

Installation

macOS

# Using Homebrew
brew install ruby

# Using rbenv (recommended for managing versions)
brew install rbenv ruby-build
rbenv install 3.3.0
rbenv global 3.3.0
echo 'eval "$(rbenv init -)"' >> ~/.zshrc

Ubuntu/Debian

# System package
sudo apt install ruby-full

# Using rbenv
sudo apt install git curl libssl-dev libreadline-dev zlib1g-dev
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
source ~/.bashrc
rbenv install 3.3.0
rbenv global 3.3.0

Using RVM

curl -sSL https://get.rvm.io | bash -s stable
source ~/.rvm/scripts/rvm
rvm install 3.3.0
rvm use 3.3.0 --default

Core Language

Data Types

TypeExampleDescription
Integer42, 0xFF, 1_000_000Arbitrary precision
Float3.14, 1.5e3Double precision
String"hello", 'literal'Mutable text
Symbol:name, :"complex name"Immutable identifiers
Array[1, "two", :three]Ordered collection
Hash{key: "value"}Key-value pairs
Range(1..10), (1...10)Inclusive / exclusive
Booleantrue, falseTrueClass / FalseClass
NilnilNilClass (absence of value)
Regexp/pattern/iRegular expression

String Operations

# String interpolation (double quotes only)
name = "Ruby"
puts "Hello, #{name}!"

# Multi-line strings
text = <<~HEREDOC
  This is a
  multi-line string
HEREDOC

# Common methods
"hello".upcase          # => "HELLO"
"Hello World".split     # => ["Hello", "World"]
"  trim  ".strip        # => "trim"
"hello".chars           # => ["h", "e", "l", "l", "o"]
"hello" * 3             # => "hellohellohello"
"hello".gsub(/l/, "r")  # => "herro"
"hello".freeze          # Make immutable

Arrays and Hashes

# Array operations
arr = [3, 1, 4, 1, 5, 9]
arr.push(2)              # Append
arr.unshift(0)           # Prepend
arr.select { |x| x > 3 } # => [4, 5, 9]
arr.map { |x| x * 2 }    # Transform
arr.reduce(:+)            # Sum all
arr.sort.uniq             # Sort and deduplicate
arr.each_with_index { |val, i| puts "#{i}: #{val}" }
arr.flat_map { |x| [x, x * 2] }
arr.group_by { |x| x > 3 ? :big : :small }

# Hash operations
user = { name: "Alice", age: 30, role: :admin }
user[:name]              # => "Alice"
user.fetch(:email, "n/a") # With default
user.merge(email: "a@b.com")
user.select { |k, v| v.is_a?(String) }
user.transform_values(&:to_s)

Control Flow

# Conditional
if score >= 90
  "A"
elsif score >= 80
  "B"
else
  "C"
end

# Inline conditional
status = age >= 18 ? "adult" : "minor"
puts "Hello" if logged_in?
puts "Error" unless valid?

# Case expression
case command
when "start" then start_server
when "stop"  then stop_server
when /quit/i then exit
else puts "Unknown command"
end

# Pattern matching (Ruby 3+)
case response
in { status: 200, body: String => body }
  process(body)
in { status: 404 }
  not_found
in { status: (500..) }
  server_error
end

Blocks, Procs, and Lambdas

# Block
[1, 2, 3].each { |n| puts n }
[1, 2, 3].each do |n|
  puts n
end

# Proc
square = Proc.new { |x| x ** 2 }
square.call(5) # => 25

# Lambda (strict arity)
multiply = ->(a, b) { a * b }
multiply.call(3, 4) # => 12

# Method accepting block
def with_logging
  puts "Start"
  result = yield
  puts "End"
  result
end

with_logging { expensive_operation }

Object-Oriented Programming

class Animal
  attr_accessor :name
  attr_reader :species

  def initialize(name, species)
    @name = name
    @species = species
  end

  def speak
    raise NotImplementedError
  end

  protected

  def internal_id
    object_id
  end

  private

  def secret
    "hidden"
  end
end

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

# Modules as mixins
module Loggable
  def log(message)
    puts "[#{self.class}] #{message}"
  end
end

class Service
  include Loggable  # Instance methods
  extend Loggable   # Class methods
end

Gems and Bundler

# Install a gem
gem install nokogiri

# Create Gemfile
bundle init

# Install dependencies
bundle install

# Update gems
bundle update

# Execute in bundle context
bundle exec ruby script.rb
# Gemfile
source "https://rubygems.org"

gem "rails", "~> 7.1"
gem "pg", ">= 1.5"
gem "puma", "~> 6.0"

group :development, :test do
  gem "rspec-rails"
  gem "rubocop", require: false
end

Configuration

.ruby-version

3.3.0

IRB Configuration (.irbrc)

require 'irb/completion'
IRB.conf[:AUTO_INDENT] = true
IRB.conf[:SAVE_HISTORY] = 1000
IRB.conf[:PROMPT_MODE] = :SIMPLE

Advanced Usage

Metaprogramming

class User
  FIELDS = [:name, :email, :age]

  FIELDS.each do |field|
    define_method(field) { instance_variable_get("@#{field}") }
    define_method("#{field}=") { |val| instance_variable_set("@#{field}", val) }
  end

  def method_missing(method, *args)
    if method.to_s.start_with?("find_by_")
      field = method.to_s.sub("find_by_", "")
      # dynamic finder logic
    else
      super
    end
  end
end

Fiber and Ractor (Ruby 3+)

# Fiber for cooperative concurrency
fiber = Fiber.new do
  Fiber.yield 1
  Fiber.yield 2
  3
end
fiber.resume # => 1
fiber.resume # => 2
fiber.resume # => 3

# Ractor for parallel execution
ractor = Ractor.new do
  msg = Ractor.receive
  msg * 2
end
ractor.send(21)
ractor.take # => 42

Testing with RSpec

RSpec.describe User do
  describe "#full_name" do
    it "returns first and last name" do
      user = User.new(first: "Alice", last: "Smith")
      expect(user.full_name).to eq("Alice Smith")
    end
  end

  context "when email is invalid" do
    it "raises a validation error" do
      expect { User.create!(email: "bad") }.to raise_error(ActiveRecord::RecordInvalid)
    end
  end
end

Troubleshooting

ProblemSolution
LoadError: cannot load such fileCheck gem is in Gemfile; run bundle install
Gem::FilePermissionErrorUse rbenv/rvm instead of system Ruby; never sudo gem install
Encoding issuesAdd # encoding: utf-8 or set Encoding.default_external = Encoding::UTF_8
NoMethodError: undefined method for nilCheck for nil with &. safe navigation operator
Slow startupUse bootsnap gem; enable YJIT with --yjit flag (Ruby 3.2+)
Memory bloatProfile with memory_profiler gem; check for object retention
Bundle conflictsRun bundle update or check version constraints in Gemfile
Segfault in native extensionEnsure build tools installed: build-essential, libffi-dev