Ruby Tutorial
Learn Ruby 4.0 from your first script to blocks, objects, modules, metaprogramming, the standard library, concurrency and real projects. 134 lessons with Ruby that compiles and runs in your browser, quizzes and projects.
Start learning →
of lessons completed
Getting Started
- Introduction to Ruby Meet Ruby 4.0, the readable object-oriented language behind Rails. Learn its history, philosophy, where it runs and write real code in your browser.
- Your First Ruby Program Write and run your first Ruby script. Learn puts, print and p, comments, how the interpreter reads a file and how to read syntax errors, with live examples.
- How Ruby Runs See what happens when you run a Ruby file - parser, bytecode, the virtual machine, YJIT and ZJIT - plus how irb, gems, Bundler and version managers fit together.
- Variables and Constants Learn how Ruby variables really work - references, naming rules, local scope, constants, global and instance variables, multiple assignment and freezing.
- Predefined Variables, Global Variables and BEGIN/END Blocks Learn Ruby's predefined variables and constants - $0, $PROGRAM_NAME, ARGV, ENV, $stdout, $stderr, $~, $1, $!, $/ - plus your own globals, their pitfalls, and BEGIN, END and at_exit blocks.
- Basic Types Tour Ruby's basic types - Integer, Float, String, Symbol, true, false and nil. Learn class, is_a?, truthiness, conversions and the errors that wrong types cause.
- Numbers Master Ruby numbers - integer division, modulo, big integers, float precision, rounding, Rational, Complex, Integer methods and the Math module, with examples.
- Strings Learn Ruby strings - single and double quotes, escapes, interpolation, heredocs, concatenation, mutability, frozen string literals and the chilled string warning.
- String Methods A practical tour of Ruby string methods - length, case, strip, split, sub and gsub, slicing, padding, searching, chars, each_line and encoding basics, with examples.
- Symbols Understand Ruby symbols - what they are, how they differ from strings, to_sym and to_proc, hash keys, memory behavior, when to use each and common pitfalls.
- Reading Input and Formatting Output Read input with gets and STDIN, print with puts, print, p and pp, and format numbers and tables with format, printf and the percent operator in Ruby.
- Operators Learn Ruby operators - arithmetic, comparison, the spaceship, logical && and and, assignment and ||=, safe navigation, ranges, bitwise ops and precedence rules.
Control Flow
- if, elsif, else and unless Learn Ruby conditionals - if, elsif, else, unless, modifier forms, conditionals as expressions, truthiness (only nil and false are falsy), guard clauses and common pitfalls.
- case and when Learn Ruby's case expression - matching values, ranges, classes, regexes and lambdas with ===, comma lists, then, else, and case without a subject.
- Pattern Matching Learn Ruby pattern matching - case/in with arrays, hashes, find patterns, guards, the pin operator, deconstruct, deconstruct_keys, and the => and in operators.
- Loops Learn Ruby loops - while, until, loop, for and why it is rarely used, break with a value, next, redo, loop modifiers, begin/end while, and infinite loops.
- Iterators and Blocks Basics Learn the Ruby way to loop - each, times, upto, downto, step, each_with_index, each_char and friends, how blocks work, block parameters, and the implicit it parameter.
- Ranges Learn Ruby ranges - inclusive and exclusive, endless and beginless ranges, step and %, each, to_a, include? versus cover?, case/when, slicing and lazy use.
- Ternary, Safe Navigation and Short-Circuit Learn Ruby's compact conditionals - the ternary operator, safe navigation &., short-circuit && and ||, ||= and &&=, and idioms for handling nil without errors.
- Exceptions Learn Ruby exception handling - begin/rescue/else/ensure, raise, retry, the exception hierarchy, rescue modifiers, backtraces and full_message, with runnable examples.
- Custom Exceptions Learn to write custom exception classes in Ruby - subclassing StandardError, error hierarchies, extra data, default messages, cause, exit codes and best practices.
- catch and throw Learn Ruby's catch and throw for non-local exits from nested loops and methods, how they differ from exceptions and break, UncaughtThrowError, and when to avoid them.
- Immutability and freeze Learn Ruby immutability - freeze, frozen?, FrozenError, frozen string literals, dup vs clone, constants, deep freezing and Ractor.make_shareable, with examples.
- Loop Control: redo, retry and next/break in Blocks Master Ruby flow control inside blocks and loops - next and break values, redo, retry in rescue, StopIteration, LocalJumpError, and how to leave nested loops cleanly.
Methods and Blocks
- Methods Learn how to define and call Ruby methods - def, implicit return, multiple return values, predicate and bang naming, default arguments, scope and good method design.
- Method Arguments Master Ruby method parameters - positional, optional, splat, keyword, required keyword, double splat, block arguments and argument forwarding with ... and anonymous * ** &.
- Blocks Learn Ruby blocks from scratch - yield, block_given?, passing arguments, the &block parameter, block-local variables and how return, break and next behave.
- Procs and Lambdas Understand Ruby procs and lambdas - how they differ in arguments and return, arity, closures, curry, composition, Method objects and Symbol#to_proc, with examples.
- Closures and Binding Learn how Ruby closures capture variables, what scope gates (def, class, module) do, how to share state with define_method, and how to inspect a Binding object.
- Enumerators and Lazy Enumerators Learn Ruby Enumerator objects - external iteration with next and peek, Enumerator.new, to_enum, Enumerator.produce, and Enumerator::Lazy for infinite sequences.
- Fibers Learn Ruby Fibers - lightweight, pausable code blocks with resume and Fiber.yield, generators, passing values, round-robin scheduling and the Fiber scheduler idea.
- method_missing and respond_to_missing? Learn how Ruby's method_missing builds ghost methods, why respond_to_missing? must come with it, how to avoid infinite recursion, and when define_method is better.
- Refinements Learn Ruby refinements - refine and using, file and class scope, super inside a refinement, import_methods, and when refinements beat monkey patching.
- Recursion Learn recursion in Ruby - base cases, tracing calls, SystemStackError and stack depth, memoization with Hash default procs, tail calls, and turning recursion into loops.
- Endless Methods and Modern Syntax Modern Ruby syntax explained - endless methods, the it block parameter, numbered parameters, hash shorthand like {x:, y:}, and anonymous argument forwarding.
- Method Objects, Currying and Composition Treat methods as values in Ruby. Learn Method and UnboundMethod, bind, super_method, curry, partial application and composing functions with >> and <<, with runnable examples.
Collections
- Arrays Learn Ruby arrays - creating them, indexing and slicing, adding and removing elements, concat, flatten, compact, copies, and common errors, with runnable examples.
- Iterating and Transforming Arrays Learn Ruby array iteration and transformation - each, map, select, reject, reduce, each_with_object, partition, group_by, zip, flat_map, with step-by-step examples.
- Sorting and Searching Arrays Learn how to sort and search Ruby arrays - sort, sort_by, min and max, binary search with bsearch, include?, index, find, sum, tally and uniq, with runnable code.
- Hashes Learn Ruby hashes from scratch - symbol keys, reading with [] and fetch, default values, iteration, merge, delete, dig, transform_values and the pitfalls that trip up beginners.
- Hash Patterns Learn the everyday hash recipes in Ruby - counting with tally and Hash.new(0), grouping, nested hashes with default procs, inverting, compare_by_identity and insertion order.
- Sets Learn Ruby's Set class - creating sets, adding and removing, fast membership tests, union, intersection, difference, subset checks, sets of objects and when to use a Set over an Array.
- Struct and Data Learn Ruby's Struct and Data.define for small data-carrying classes - positional and keyword arguments, equality, immutability, with, pattern matching, and when to choose each.
- The Enumerable Module Learn Ruby's Enumerable module - the dozens of methods you get by defining each, building your own collection classes, to_enum, lazy evaluation, and Enumerable versus Comparable.
- Comparable Learn Ruby's Comparable module - define the spaceship operator <=> once and get <, >, ==, between? and clamp, sort and min/max custom objects, handle nil results and compare safely.
- Array Algorithms Learn Ruby array algorithms - combination, permutation, product, each_slice, each_cons, transpose, rotate, zip, and seeded shuffle and sample - with runnable examples.
- Slices and Indexing in Depth Master Ruby array and string indexing - negative indices, ranges as indexes, start and length slices, slice!, values_at, fetch, fetch_values and dig, with runnable examples.
- Stacks, Queues and Other Structures Build stacks, queues, priority queues and linked lists in Ruby - Array as stack and queue, Queue and SizedQueue, a binary heap and a hand-written list - with runnable examples.
Object-Oriented Ruby
- Classes and Objects Learn Ruby classes and objects - class, new, initialize, instance variables, attr_reader, attr_writer, attr_accessor, instance methods, to_s and inspect - with runnable examples.
- Instance and Class Methods Understand Ruby instance methods versus class methods - what self means, def self.method, class << self, class instance variables, and why class variables (@@) are risky.
- Inheritance Learn Ruby inheritance - subclasses with <, overriding methods, super with and without arguments, the ancestors chain, Object and BasicObject, abstract methods, and when to prefer composition.
- Modules and Mixins Learn Ruby modules - namespaces, mixins with include, extend and prepend, ancestors and method lookup, module constants, module_function and when to choose a module over a class.
- public, private and protected Understand Ruby method visibility - public, private and protected, how self receivers work, private_class_method, private_constant, send versus public_send, and common mistakes.
- Equality and Identity Learn the four kinds of equality in Ruby - ==, eql?, equal? and === - how hash keys use eql? and hash, and how to write correct custom equality for your own classes.
- to_s, inspect and Conversions Learn the difference between to_s and inspect in Ruby, how puts and p use them, explicit versus implicit conversions (to_str, to_ary, to_proc) and Kernel#Integer, Float, String and Array.
- Duck Typing and Polymorphism Learn duck typing in Ruby - polymorphism without inheritance, respond_to?, interfaces by convention, NoMethodError, composition over inheritance and the null object pattern, with examples.
- Singleton Methods and the Singleton Class Learn Ruby singleton methods, the singleton class (eigenclass), class << self, define_singleton_method and how class methods really work, with runnable examples and method lookup.
- The Ruby Object Model Understand how Ruby really works - classes are objects, how method lookup walks the ancestors chain, how constants are found, and what Class, Module and BasicObject are.
- Operator Overloading Learn how Ruby operators are just method calls, and how to define +, -, ==, <=>, [], <<, unary operators, coerce and to_proc so your own classes feel built in.
- Copying Objects Learn how Ruby assignment shares objects, how dup and clone make shallow copies, how they differ, and how to write initialize_copy and deep copies safely.
- Design Principles in Ruby Apply SOLID, small objects, composition over inheritance, dependency injection and the null object pattern in idiomatic Ruby, with runnable before-and-after examples.
- Design Patterns Learn six classic design patterns in idiomatic Ruby - Observer, Strategy, Decorator, Builder, State and Command - using blocks, modules and duck typing, with runnable code.
Metaprogramming
- Introduction to Metaprogramming A friendly introduction to Ruby metaprogramming - send and public_send, define_method, instance_variable_get and set, Class.new, hooks and the rules for using it responsibly.
- define_method and Dynamic Methods Learn how Ruby define_method creates methods at runtime, how to write attr-like class macros, how closures capture values, and when plain def is better.
- Hooks and Callbacks Learn Ruby hooks: inherited, included, extended, prepended, method_added and const_missing. Build plugin registries and class-level DSLs safely.
- instance_eval and class_eval Learn how Ruby's instance_eval, class_eval, instance_exec and class_exec change self inside a block, how they differ, and how they power DSLs and test helpers.
- Building DSLs Learn how to design internal DSLs in Ruby with blocks, builder objects, instance_eval and method chaining, with working HTML, route and config examples.
- Reflection and Introspection Learn Ruby introspection: list methods and instance variables, check ancestors, use Method and UnboundMethod objects and find a method with source_location.
- Monkey Patching and Safe Alternatives Learn what monkey patching is in Ruby, why open classes are risky, and how prepend wrappers, refinements, subclasses and delegation keep code safe.
- eval and Binding Learn how Ruby's eval runs strings as code, how Binding captures local variables, why eval is a security risk, and which safer tools to reach for first.
- Ractors Learn Ruby Ractors, the actor-style way to run Ruby code in parallel. Understand isolation, message passing, ports, shareable objects and the errors you will meet.
- Native Extensions and Fiddle Call C code from Ruby. Learn how native extensions are built, how Fiddle loads shared libraries, maps types, handles pointers, structs and callbacks, and when to choose each approach.
Standard Library
- Regular Expressions A complete guide to Ruby regular expressions. Learn match, =~, captures, named groups, scan, gsub with blocks, anchors, lookarounds, flags and common pitfalls.
- Text Processing Learn practical Ruby text processing - splitting and cleaning text, counting words, parsing log files, transforming with tr and gsub, and printing aligned reports.
- Files and IO Learn to read and write files in Ruby with File and IO - open with blocks, modes, line-by-line reading, paths, directories, globbing and handling file errors.
- Tempfile, Pathname and FileUtils Work safely with temporary files and directories using Tempfile and Dir.mktmpdir, handle paths as objects with Pathname, and copy, move and delete with FileUtils.
- Time and Date Learn Ruby's Time and Date classes - creating moments, strftime formatting, arithmetic, parsing ISO 8601, time zones and offsets, calendar math with Date, and the mistakes that bite.
- Random Numbers and Math Learn random numbers and math in Ruby - rand, seeded Random generators for repeatable results, shuffle and sample, the Math module, Integer.sqrt, SecureRandom, and when randomness is safe.
- JSON Learn JSON in Ruby - JSON.parse and symbolize_names, JSON.generate and pretty_generate, writing custom to_json for your classes, handling ParserError, type mapping and common pitfalls.
- YAML and CSV Learn YAML and CSV in Ruby - YAML.dump and safe loading, permitted classes, CSV.parse with headers and converters, CSV.generate, quoting rules, malformed data errors and the CSV bundled gem.
- Set, OpenStruct and Friends Learn when to use Ruby's OpenStruct, Set and ObjectSpace::WeakMap, why OpenStruct is a bundled gem you should rarely need, what happened to SortedSet, and the better alternatives.
- Benchmarking Learn how to benchmark Ruby code - Benchmark.realtime and measure, the monotonic clock, comparing approaches fairly, counting allocations with GC.stat, warm-up, and profiling tools like stackprof.
- Digest, Base64 and Encoding Learn Ruby's Digest hashes (SHA256, HMAC), Base64 and URL-safe Base64, hex, pack and unpack, and string encodings - force_encoding vs encode, scrub, and common byte-level errors.
- URI and Networking Basics Learn Ruby's URI library (parse, join, build, query strings, encoding) and networking basics - Net::HTTP requests, a local TCPServer demo, timeouts and the exceptions that network code raises.
- OptionParser and Logger Build command-line tools with Ruby's OptionParser (flags, typed arguments, help, errors) and record what your program does with Logger (levels, formatters, progname) - all runnable in the browser.
- ERB Templates Learn ERB, Ruby's built-in template engine - output and code tags, loops, trim modes, passing data with binding and result_with_hash, HTML escaping, error line numbers and safe usage.
- StringIO and Streams Learn StringIO in Ruby - read and write a string like a file, rewind and seek, capture $stdout and $stderr, fake STDIN for tests, inject input and output streams, and avoid EOFError and IOError.
- Forwardable and Delegation Learn delegation in Ruby - Forwardable's def_delegators, SimpleDelegator and DelegateClass decorators, composition vs inheritance, and the pitfalls with equality, is_a? and private methods.
- Observable, Singleton and Standard Patterns Learn the Singleton module, the Observable pattern and Comparable in Ruby with runnable examples, test-friendly alternatives and the pitfalls of global state.
- ObjectSpace, WeakRef and the Garbage Collector Learn how Ruby's garbage collector works - GC.stat and GC.start, ObjectSpace.each_object, finalizers, WeakRef, ObjectSpace::WeakMap and WeakKeyMap, and when to tune GC.
- Zlib, Open3 and Net::HTTP Compress and decompress data with Zlib and gzip, run external commands and capture output with Open3, and make HTTP requests with Net::HTTP. Runnable loopback examples.
- BigDecimal, Rational and Complex Do exact math in Ruby - why 0.1 + 0.2 is off, BigDecimal for money, Rational fractions, Complex numbers, rounding modes, conversions and when to pick which type.
- Heredocs and sprintf/format Write multi-line strings with Ruby heredocs (<<~, <<-, quoted terminators) and format text with sprintf, format and String#% - widths, padding, precision and named fields.
Concurrency
- Threads Learn Ruby threads: Thread.new, join, value, thread-local variables, error handling, the GVL and race conditions, with runnable examples and real errors.
- Mutex, Queue and ConditionVariable Learn how Ruby threads share data safely with Mutex, Queue, SizedQueue, ConditionVariable and Monitor, with producer-consumer examples and deadlock fixes.
- Thread Pools and Parallel Work Build a Ruby thread pool with Queue, run jobs in parallel with ordered results, handle errors in worker threads, limit concurrency and use Timeout safely.
- Fibers and the Fiber Scheduler Learn how the Ruby Fiber scheduler works: non-blocking fibers, Fiber.schedule, a hand-written scheduler you can run, and what the async gem adds in projects.
- Processes and Subprocesses Learn Ruby processes: fork, Process.wait, exit status, system, backticks, spawn, Open3, pipes between processes, signals and how to avoid shell injection.
- Parallelism and Ractors Understand the Ruby GVL and learn when to use threads, Ractors or processes to use more than one CPU core. Includes Ractor-safe code rules and a decision guide.
Testing and Tooling
- Testing with Minitest Learn Minitest, the test library that ships with Ruby. Write test classes, use assertions, read failures and errors, share setup code and try the spec style.
- Test-Driven Development Learn test-driven development in Ruby with Minitest. Follow the red, green, refactor cycle step by step by building a Roman numeral converter test-first.
- RSpec Overview Learn how RSpec works in Ruby, the most popular testing gem: describe, it, expect, matchers, let, doubles. Includes a runnable mini-RSpec built from scratch.
- Test Doubles Learn how to isolate Ruby tests with fakes, stubs, spies and mocks. Use dependency injection, write your own doubles and stub methods safely with Minitest.
- Debugging Ruby Learn practical Ruby debugging: read errors and backtraces, print with p and pp, trace calls with caller and TracePoint, and use binding.irb and the debug gem.
- RubyGems and Bundler Understand RubyGems and Bundler - what a gem is, version numbers and the ~> operator, Gemfile and Gemfile.lock, bundle install and exec, and how to structure your own gem.
- Rake and Automation Learn Rake, Ruby's build and automation tool - tasks, prerequisites, namespaces, arguments, file tasks, running tasks from code, and a plain-Ruby task runner you can build yourself.
- Style and Linting Learn Ruby naming and formatting conventions, idiomatic style choices, what RuboCop checks and how to configure it, and build a small linter yourself with the Prism parser.
- Performance Tips Practical Ruby performance - measure first, pick better algorithms and data structures, build strings efficiently, avoid extra allocations, use lazy enumerators, and understand what YJIT and ZJIT do.
- Ruby Versions and Changes A tour of Ruby 3.0 through 4.0 - keyword arguments, pattern matching, endless methods, Data, the it parameter, Set in core, Ractor ports, Prism, JITs - with runnable examples and upgrade advice.
- TracePoint and Profiling Learn Ruby's TracePoint to watch method calls, returns, raises and line events, build a call counter and tracer, write a toy sampling profiler, and use stackprof.
- YJIT and Ruby Performance Internals Look under Ruby's hood. See how YJIT compiles hot code, how the garbage collector and object slots work, how to measure allocations and memory, and which habits help or hurt the JIT.
- Type Checking: RBS, Steep and Sorbet Learn gradual typing in Ruby. Write RBS signatures, parse them with the rbs library, see how Steep and Sorbet check code, and build a small runtime checker yourself.
Web and Ecosystem
- Ruby on Rails Overview A beginner's guide to Ruby on Rails - what the framework is, MVC, conventions over configuration, routing, controllers, ActiveRecord models, views, generators, plus a runnable mini-MVC in plain Ruby.
- Sinatra and Rack Learn how Ruby web apps work. Build a Rack-style app by hand, call it with a plain hash, add middleware, write a tiny Sinatra-style DSL, and read real Sinatra code.
- Database Access Ideas Learn the ideas behind Ruby database access. Build a data mapper and a tiny ActiveRecord-style model over plain arrays, count queries, spot N+1 problems, and see the real sqlite3 and Rails code.
- Scripting and Command-Line Tools Write Ruby command-line tools that behave like real Unix programs. Learn ARGV, exit codes, shebangs, STDIN pipelines, stderr, colored output, and a hand-built Thor-style command dispatcher.
- The Ruby Ecosystem A guided tour of the Ruby ecosystem - Rails and Hanami, Sidekiq-style background jobs, Jekyll-style site generators, Chef-style automation, testing tools, and what Ruby work looks like today.
- ActiveRecord and Sequel Basics Compare the two main Ruby ORMs. See how Sequel datasets and ActiveRecord models, migrations, validations, callbacks and associations work, using runnable plain-Ruby stand-ins.
- Rails MVC, Routing and Controllers Follow a Rails request from the browser to the response. Learn routes, resources, path helpers, controllers, filters, strong parameters and render versus redirect, with runnable stand-ins.
- Secure Ruby Code Write safer Ruby. Prevent SQL, shell and path injection, avoid mass assignment, load YAML and JSON safely, compare secrets in constant time, escape HTML and keep credentials out of code.
Projects
- Project: Expression Calculator Build a calculator in Ruby from scratch - a tokenizer, a recursive descent parser, an AST made of Data objects, a pattern-matching evaluator, variables, functions and good error messages.
- Project: Command-Line To-Do Manager Build a to-do manager in Ruby with Data objects, an Enumerable collection, custom errors, JSON saving and loading, pattern-matching command parsing and a scripted command loop you can run in the browser.
- Project: Bank Account Simulation Build a bank account simulation in Ruby step by step: classes, custom exceptions, a mixin audit log, Comparable accounts, transfers and a scripted command loop.
- Project: Inventory and Reports Build an inventory and reporting tool in Ruby: import CSV from a string, validate rows with Data, group and sort with hashes, and print aligned tables.
- Project: A Text Adventure Engine Build a text adventure engine in Ruby: describe rooms with a small DSL, parse commands with pattern matching, track state, and play a scripted game.
- Project: A Threaded Job Runner Build a threaded job runner in Ruby with a Queue, worker threads, per-job errors, retries and timeouts, then extend it into a small concurrent crawler.
- Project: A JSON Parser Write a JSON parser in Ruby from scratch: recursive descent with StringScanner, a Data-based tree, helpful error messages, a pretty printer and path queries.
- Project: A Tiny Web Framework Build a tiny web framework in Ruby: the Rack calling convention, request and response objects, a router with parameters, a middleware chain and tests that call the app directly.
Practice
- Ruby Cheat Sheet A Ruby 4.0 cheat sheet with runnable examples for variables, strings, collections, blocks, classes, pattern matching and errors.
- Common Ruby Mistakes The Ruby mistakes everyone makes, with real error messages. Nil errors, shared defaults, string aliasing, scope and procs, and the fix for each.
- Ruby for Developers from Other Languages A practical guide to the differences between Ruby and Python, JavaScript, Java and PHP. Truthiness, numbers, blocks, objects, errors and modules, with runnable code.
- Ruby Interview Questions Forty Ruby interview questions with clear answers and runnable code, from truthiness and blocks to the object model, metaprogramming, exceptions and concurrency.
- Practice Problems: Arrays, Strings and Hashes Eight interview-style Ruby exercises on arrays, strings and hashes - two sum, anagrams, parentheses, sliding window, intervals - with hints, tested solutions and complexity notes.
- Practice Problems: OOP and Metaprogramming Seven Ruby exercises on classes, Comparable, Enumerable, class-level macros, method_missing proxies, instance_eval DSLs and prepend, each with a hint and a tested solution.