🚀 Ruby Introduction
🎯 Complete Definition
Ruby is a dynamic, open-source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. Created by Yukihiro "Matz" Matsumoto and released in 1995, Ruby's design philosophy emphasizes that "everything is an object" and prioritizes developer happiness. It combines features from Perl, Smalltalk, Eiffel, Ada, and Lisp.
🔬 Core Characteristics
- Pure Object-Oriented: Everything is an object, including numbers and booleans
- Dynamic Typing: Types are checked at runtime, variables have no type
- Interpreted: Executed via MRI (Matz's Ruby Interpreter), YARV, or alternative VMs
- Flexible Syntax: Parentheses optional, powerful blocks/closures
- Automatic Memory Management: Garbage collection (mark & sweep, incremental)
- Mixins: Modules provide multiple inheritance-like behavior
- Metaprogramming: Code that writes code at runtime (open classes, method_missing)
📊 Industry Usage
Ruby on Rails revolutionized web development. Used by GitHub, Shopify, Airbnb, Basecamp, Stripe, and thousands of startups. Ruby ranks consistently in top 10 languages (TIOBE, RedMonk). Powers massive e-commerce platforms, automation scripts, and prototyping. RubyGems hosts over 150,000 libraries.
📊 Variables & Data Types
🎯 Complete Definition
Variables in Ruby are references to objects. Ruby uses dynamic typing: variable types are determined by the object they reference. Variable names indicate scope: local (lowercase/underscore), instance (@), class (@@), global ($), and constants (Uppercase). Ruby's core data types include Numbers (Integer, Float), Strings, Symbols, Booleans, Arrays, Hashes, Ranges, and nil.
🏷️ Core Data Types
- Integer: Arbitrary precision (Fixnum/Bignum merged into Integer)
- Float: Double-precision floating point
- String: Mutable sequence of characters (UTF-8 by default)
- Symbol: Immutable, interned identifiers (:symbol)
- Array: Ordered, zero-based, dynamically growing collection
- Hash: Key-value dictionary (ordered since 1.9)
- TrueClass / FalseClass / NilClass: true, false, nil
- Range: (1..10) inclusive, (1...10) exclusive
🔧 Advanced Features
Parallel assignment, swapping variables: a,b = b,a. Everything returns a value. Constants emit warnings when reassigned. Symbol immutability saves memory and speeds up hash lookups. Freezing objects with .freeze makes them immutable.
🔢 Operators
🎯 Complete Definition
Operators are actually method calls in Ruby (syntactic sugar). Most operators like +, -, == are methods invoked on the left object. Ruby provides a rich set of operators with defined precedence and associativity. All operators can be overridden in custom classes except a few (&&, ||, .., ...).
📋 Operator Categories
- Arithmetic: +, -, *, /, %, ** (exponentiation)
- Comparison: ==, !=, >, <, >=, <=, <=> (spaceship), .eql?, equal?
- Logical: &&, ||, !, and, or, not (low precedence versions)
- Bitwise: &, |, ^, ~, <<, >> (for integers)
- Assignment: =, +=, -=, *=, /=, %=, **=, &=, |=, ^=, <<=, >>=
- Range: .. (inclusive), ... (exclusive)
- Ternary: condition ? true_expr : false_expr
- Misc: defined?, :: (scope), . (method call)
⚡ Precedence (high to low)
[] []= > ** > ! ~ + (unary) > * / % > + - > << >> > & > | ^ > > < >= <= > <=> == === != =~ !~ > && > || > .. ... > ?: > = += ... > defined? > not > and or
🔀 Control Flow
🎯 Complete Definition
Control flow in Ruby uses if/unless/case. Everything is an expression (returns a value). Modifier forms (puts "x" if x) allow concise syntax. Ruby also has until as opposite of while, and case with === operator (case equality).
🏗️ Control Structures
- if / elsif / else: Traditional conditional
- unless: Execute if condition is false
- case / when: Multi-way branch using ===
- ternary: inline condition ? a : b
- statement modifiers: action if condition, action unless condition
- defined?: Check if expression defined
🔍 Truthiness
Only false and nil are falsy; everything else is truthy (including 0, "", []). This is different from many languages.
🔄 Loops & Iterators
🎯 Complete Definition
Ruby provides traditional loops (while, until) and powerful iterator methods (each, times, upto, step). for is syntactic sugar for each. Loop control: break, next, redo, retry. Most idiomatic Ruby uses iterators.
🏗️ Loop Types
- while condition: Execute while condition truthy
- until condition: Execute while condition falsy
- for item in collection: (uses each internally)
- Integer.times: Iterate block n times
- upto/downto: Range iteration
- each: Basic iterator for collections
- loop: Infinite loop (break to exit)
⚡ Loop Controls
break: exits loop. next: jumps to next iteration. redo: repeats current iteration. retry: restarts loop (works in certain contexts).
⚙️ Methods
🎯 Complete Definition
Methods define behavior for objects. Defined with def keyword, end with end. Return last evaluated expression unless explicit return. Methods can have default arguments, variable arguments (*args), keyword arguments, and block arguments (&block). Methods names can end with ? (predicate), ! (dangerous/bang), = (setter).
🏗️ Method Features
- def name(params): Standard definition
- default parameters: def greet(name="Ruby")
- *args: Splat operator captures variable args
- **kwargs: Keyword args (Ruby 2.0+)
- &block: Capture block as Proc
- return: Explicit return (optional)
🔧 Method Visibility
public (default), protected, private. Private methods cannot be called with explicit receiver. Methods are objects (can be stored) via method(:name).
📋 Arrays
🎯 Complete Definition
Array is an ordered, integer-indexed collection of objects. Arrays can hold any type (heterogeneous). Indexing starts at 0, negative indexes count from end. Arrays are dynamic (grow/shrink). Rich set of methods: stack/queue operations, set operations, filtering, sorting.
🏗️ Array Operations
- [] / at: element access
- << / push / unshift: add elements
- pop / shift: remove from end/start
- concat / +: concatenation
- each / map / select / reject: iterators
- join / split: string conversion
- include? / index / rindex: search
- sort / reverse / uniq: transformation
⚡ Performance
Array access O(1), amortized push O(1), insertion/deletion O(n). Ruby 3.x optimizes small arrays.
🔑 Hashes
🎯 Complete Definition
Hash is a dictionary-like collection of unique keys and their values. Keys can be any object (Symbols preferred). Hashes maintain insertion order (since Ruby 1.9). Default values can be provided. Hashes are often used for named parameters, data structures.
🏗️ Hash Operations
- {} / Hash.new: create
- [] / fetch: value access
- []= / store: assign
- keys / values: get keys/values arrays
- each / map: iteration
- merge / update: combine hashes
- transform_keys / transform_values: Ruby 2.4+
- dig: nested access (Ruby 2.3+)
🔧 Advanced
Symbol keys: hash = {name: "Ruby", age: 25} (new syntax). fetch raises or returns default. default_proc for dynamic defaults.
📝 Strings
🎯 Complete Definition
String in Ruby is a mutable sequence of characters (encoding-aware). Supports interpolation ("#{}"), concatenation (+), repetition (*), and a huge standard library. Strings are objects with over 100 methods. %Q and %q provide alternative quoting. Heredocs support multiline.
🏗️ String Operations
- length / size / empty?: size info
- + / << / concat: concatenation
- split / join: convert to/from arrays
- strip / chomp / chop: trimming
- upcase / downcase / capitalize: case
- gsub / sub: substitution
- include? / index / start_with?: search
- to_i / to_f / to_sym: conversion
⚡ Performance
Strings are mutable (can be changed). Use "" for mutable, '' for literal (no interpolation). Frozen strings (Ruby 3+) optimize memory via # frozen_string_literal: true.
💾 File I/O
🎯 Complete Definition
File class provides interface to filesystem. Open modes: "r", "w", "a", "r+", "w+", "a+", with binary modifier ("b"). Block form auto-closes file. IO superclass provides low-level I/O. FileUtils for file operations (cp, mv, rm). Pathname for path manipulation.
🏗️ File Operations
- File.open(filename, mode): open file
- file.read / readlines: read content
- file.write / <<: write
- file.close: manual close
- File.exist? / file? / directory?: checks
- Dir.glob / Dir.entries: directory listing
- FileUtils.mv / cp / rm: high-level ops
🔧 Advanced
IO#each_line yields lines. File.read slurps entire file. File.foreach streams line by line. Tempfile for temporary files.
🛡️ Exceptions
🎯 Complete Definition
Exceptions handle errors. Hierarchy: Exception (parent) -> StandardError (common) -> subclasses. begin/rescue/else/ensure/end block. raise triggers exception. rescue can specify exception classes. ensure runs always (cleanup). retry in rescue repeats begin block.
🏗️ Exception Handling
- begin ... rescue ... end: basic block
- rescue => e: capture exception object
- rescue TypeError, ArgumentError: specific types
- else: runs if no exception
- ensure: runs always
- raise "msg": raise RuntimeError
🔧 Custom Exceptions
Define subclass of StandardError. $! global contains last exception. backtrace method shows stack.
🏗️ Object Oriented Programming
🎯 Complete Definition
Ruby is pure OOP — every object is an instance of a class. Classes define state (instance variables) and behavior (methods). Supports single inheritance, mixins (modules), and open classes. attr_accessor creates getters/setters. initialize is constructor. self refers to current object.
🏗️ OOP Features
- class Name ... end: class definition
- initialize(params): constructor
- @var: instance variable
- @@var: class variable
- attr_reader / attr_writer / attr_accessor: shortcuts
- self.method: class method
- inheritance: class Child < Parent
- super: call parent method
🔧 Advanced
method_missing, define_method, send, respond_to?. Open classes allow monkey patching. prepend for method wrapping.
📦 Modules
🎯 Complete Definition
Modules are collections of methods and constants. They cannot be instantiated. Used as namespaces and mixins. include adds module methods as instance methods. extend adds them as class methods. prepend prepends methods (Ruby 2.0+). require loads external files/gems.
🏗️ Module Features
- module M ... end: definition
- include M: mixin as instance methods
- extend M: mixin as class methods
- prepend M: method lookup before class
- require 'file': load library
- include Comparable / Enumerable: standard mixins
🔧 Standard Modules
Kernel (puts, require), Comparable (requires <=>), Enumerable (requires each), Math, FileUtils. Load path: $LOAD_PATH.
⚡ Blocks & Advanced
🎯 Complete Definition
Blocks are anonymous chunks of code passed to methods (do...end or {...}). Procs are block objects (reusable). Lambdas are Procs with strict arity and return behavior. Closures capture surrounding variables. yield calls passed block. &block captures block as Proc.
🏗️ Advanced Concepts
- yield: invoke block
- block_given?: check if block passed
- Proc.new / proc: create Proc
- lambda: create lambda
- &: & converts symbol to proc (e.g., &:to_s)
- Enumerable: map, select, inject
- method_missing: dynamic dispatch
- define_method: dynamic method creation
🔥 Metaprogramming
send, define_method, method_missing, class_eval, instance_eval — Ruby's power to write code that writes code.