Ruby Tutorial
A readable, friendly language loved for web apps and scripting.
Getting started4 lessons
Basics20 lessons
- 5Variables and StringsDynamic typing and interpolation.
- 6Numbers and ConditionsMath and branching.
- 7Ruby VariablesVariables need no declaration.
- 8Ruby Data TypesCore types: Integer, Float, String, Symbol, Array, Hash, Range, true, false and nil.
- 9Ruby Type Conversionto_i, to_f, to_s, to_a and to_sym convert values.
- 10Ruby Input and Outputputs prints a line, print does not add a newline, p shows an inspected value and gets read.
- 11Ruby Booleans and Comparisontrue and false are objects.
- 12Ruby SymbolsA symbol is an immutable name written :name.
- 13Constants, Globals and Special VariablesConstants start with a capital letter.
- 14Everything is an ObjectEven numbers and nil are objects with methods.
- 15Variables and ConstantsLocal variables start with a lowercase letter.
- 16Everything Is an ObjectNumbers, strings and nil are objects with methods.
- 17NumbersIntegers are unlimited.
- 18StringsUse single or double quotes.
- 19String Methodsupcase, downcase, capitalize, strip, split, gsub, include?, start_with?, reverse and cente.
- 20SymbolsA symbol is a lightweight unchangeable name like :ok.
- 21nil and TruthinessOnly false and nil are falsy.
- 22OperatorsArithmetic, comparison, logical, ranges and the spaceship <=>.
- 23puts, print and pputs adds a newline, print does not and p shows the inspect form.
- 24Type Conversionto_i, to_f, to_s, to_a and Integer() convert values.
Strings and numbers9 lessons
- 25Ruby Strings In DepthStrings are mutable.
- 26Heredocs and FormattingA heredoc holds multi line text.
- 27Ruby NumbersIntegers have no size limit.
- 28Random and Timerand and Random give random numbers, and Time handles dates.
- 29Heredocs and formatHeredocs write long text.
- 30Regular Expressions=~ and match test patterns.
- 31Formatting Numbersround, floor, ceil and to_s with padding format numbers.
- 32TimeTime.now, Time.new and strftime handle dates.
- 33Math and RandomMath has sqrt, sin, PI and more.
Control flow10 lessons
- 34Ruby If, Unless and Ternaryif and elsif choose branches, unless runs when a condition is false, and statement modifie.
- 35Ruby Casecase matches a value with when clauses using ===.
- 36While, Until and Loopwhile repeats while true, until repeats until true and loop do runs forever until break.
- 37Ruby Iteratorseach, times, upto, downto, step and each_with_index cover almost all loops.
- 38if, elsif, else and unlessConditions can end with a modifier.
- 39case Expressionscase matches a value against when clauses, including ranges, classes and regexes.
- 40Loopswhile, until, loop do, times, upto and step repeat code.
- 41each, map and selectIterate with each, transform with map and filter with select and reject.
- 42break, next and redobreak exits a loop, next skips to the next round.
- 43Rangesa..b includes b, a...b excludes it.
Collections15 lessons
- 44Arrays and HashesLists and dictionaries.
- 45Loops and Iteratorseach, times and while.
- 46Ruby Arrays In DepthArrays grow automatically.
- 47Array Methods: map, select, reducemap transforms, select and reject filter, reduce combines, sum adds, min and max find extr.
- 48Ruby Hashes In DepthA hash maps keys to values.
- 49Ranges and SetsRanges represent sequences, and to_a expands them.
- 50Enumerable and LazyAny class that defines each and includes Enumerable gets map, select, sort and more.
- 51ArraysArrays grow automatically.
- 52Array Methodssort, reverse, uniq, flatten, compact, include?, index, sample and zip.
- 53sort_by, min_by, group_bysort_by, min_by, max_by and group_by work with a block.
- 54HashesHashes map keys to values.
- 55Hash Methodsselect, map, transform_values, merge, sort_by, to_a and each_with_object.
- 56Counting and Tallyingtally counts items and count counts matches.
- 57SetSet stores unique values.
- 58Destructuring and SplatAssign several values at once, use * to collect the rest and ** for keywords.
Methods and blocks11 lessons
- 59Method ArgumentsMethods accept default values, keyword arguments, splat *args and double splat **opts.
- 60Blocks, Yield and ProcsA block is code passed to a method.
- 61Closures and Method ObjectsBlocks and lambdas capture the variables around them.
- 62Ruby Recursion and MemoizationA method can call itself.
- 63Methodsdef defines a method.
- 64Blocks and yieldA block is code passed to a method.
- 65Procs and LambdasProcs and lambdas are saved blocks.
- 66Variable Arguments*args collects extra arguments and **opts collects keywords.
- 67Method Chaining and Symbols to ProcChain methods and use &:method as a shortcut for a block.
- 68RecursionA method can call itself.
- 69Variable ScopeMethods have their own scope.
Methods and classes3 lessons
Object oriented Ruby14 lessons
- 73Ruby InheritanceA class inherits from one parent with <.
- 74Modules and MixinsA module groups methods and constants.
- 75Public, Private and ProtectedMethods are public by default.
- 76Class Methods and Constantsdef self.name defines a class method.
- 77Struct, Comparable and to_sStruct builds small data classes.
- 78Duck Typing and PolymorphismRuby cares what an object can do, not what class it is.
- 79ClassesA class holds data and behaviour.
- 80attr_reader, writer and accessorattr_* define getters and setters in one line.
- 81Inheritance and super< inherits.
- 82Modules and MixinsA module groups methods.
- 83Class Methods and Variablesdef self.name makes a class method.
- 84public, private, protectedprivate methods are only callable inside the object.
- 85to_s, inspect and ComparableDefine to_s for printing and include Comparable plus <=> for ordering.
- 86StructStruct makes a small class with accessors in one line.
Errors and files12 lessons
- 87Ruby Exceptionsbegin, rescue, else, ensure and retry handle errors.
- 88Ruby File I/OFile.open with a block closes the file automatically.
- 89JSON and YAMLThe json library converts Ruby hashes and arrays to text with to_json and JSON.parse back.
- 90Regular ExpressionsRegexes live between slashes.
- 91begin, rescue, ensureHandle errors with rescue.
- 92Custom ErrorsSubclass StandardError for your own errors.
- 93Reading and Writing FilesFile.write, File.read and File.foreach handle files.
- 94JSONrequire json then to_json and JSON.parse convert data.
- 95Enumerable and each_sliceClasses with each can include Enumerable to get map, select, sort and more.
- 96Practice: Word FrequencySplit, downcase and tally.
- 97Practice: FizzBuzzCombine ranges and case.
- 98Practice: Simple Bank AccountCombine classes, errors and formatting.
Advanced RubyPremium5 lessons
- 99Metaprogramming BasicsRuby code can write code.
- 100Freezing, Immutability and Dupfreeze makes an object read only.
- 101Pattern Matchingcase/in matches structure: arrays, hashes and classes.
- 102Threads, Mutex and FibersThread runs code concurrently, Mutex protects shared data and Queue passes messages.
- 103Operator Overloading and DSLsDefine operators like +, ==, [] and << on your own classes.
Ruby in practicePremium8 lessons
- 104Gems and BundlerA gem is a packaged Ruby library.
- 105Testing with RSpec and MinitestMinitest ships with Ruby, and RSpec reads like English.
- 106Web Apps with SinatraSinatra is a tiny web framework: each route is a block.
- 107Ruby on Rails OverviewRails is a full stack framework with models, views and controllers.
- 108Active Record BasicsActive Record turns tables into classes.
- 109Command Line ScriptsARGV holds arguments, gets reads input, and OptionParser parses flags.
- 110Performance and StylePrefer built in methods, avoid repeated work, use symbols and each_with_object, and profil.
- 111Ruby Best PracticesWrite small methods, name things clearly, prefer composition, keep classes focused, test e.