Explain it simply
Ruby in plain words
Ruby is a programming language created by Yukihiro "Matz" Matsumoto and first released in the mid-1990s. Its main design goal is simple: writing code should be pleasant for the person doing it. That is why a line such as 3.times { puts "Hello" } reads almost like an English sentence, and why many people find Ruby friendly as a first or second language.
Many people hear about Ruby through Rails, a web framework written in it. This course teaches Ruby itself first. Picture Ruby as a patient assistant that reads a plain text file from top to bottom and does exactly what each line says. You will notice that no separate build step of your own stands between writing code and seeing it run.
Problem → Why → Solution
The problem: without a map, Ruby code looks like magic
Open almost any Ruby tutorial about the web and you meet code like the snippet below. It is only four lines, but a beginner cannot say what half of it means: what is that colon in :desc, why does @articles have an at sign, why can a method be chained onto a class name, and what does < do on the first line? Without a map, every unfamiliar piece looks like magic, and people either copy it blindly or give up.
This course is that map. Each of the 34 lessons adds one idea, in an order where nothing needs a word you have not met yet. By the end of the Advanced chapter the snippet above is ordinary vocabulary: a class that inherits from another class, a method, an instance variable, a chain of method calls, and symbols used as hash keys.
# Typical web code: how many separate ideas can you count?
class ArticlesController < ApplicationController
def index
@articles = Article.where(published: true).order(created_at: :desc)
end
endWhy a map matters
Ruby code is dense on purpose: one line can use a class, a method call, a symbol and a hash all at once. If you learn the pieces separately and in order, the dense line becomes quick to read. If you meet them all at once inside a framework, you cannot tell which part is Ruby and which part is Rails.
Core concept: a language, an interpreter and a toolkit
Ruby is three things that work together. The first is the language: it is interpreted, dynamically typed and object-oriented, which means variables carry no declared types and almost every value, even the number 5 and even nil, is an object that you can call methods on. The second is the interpreter, the ruby command that reads your file and carries it out; the standard implementation is called CRuby, and others such as JRuby exist. The third is the toolkit that arrives with it: irb for experiments, gem for installing libraries, bundle for managing a project's libraries, and Minitest for writing tests.
| Part | What it gives you |
|---|---|
| The language | Objects and methods everywhere, blocks, symbols, readable syntax |
| The interpreter | The ruby command: ruby file.rb runs a program, ruby -v shows the version |
| The toolkit | irb for experiments, gem and bundle for libraries, Minitest for tests |
All of that sits behind one daily loop. You write a .rb file, you run it with ruby, and you read what it printed. Ruby reads the whole file first and stops straight away if the syntax is broken, so a typo on line 12 means nothing runs at all. If the syntax is fine, Ruby executes the file from the first line to the last. When something goes wrong while running, the program stops at that line, and any output printed before it is still on the screen.
1. Write
Save your code in a file that ends in .rb. Ruby needs no main method; it simply starts at the top line of the file.
2. Run
In a terminal, type ruby followed by the file name, for example ruby welcome.rb.
3. Read the output
The text sent by puts appears in the terminal. If there is an error, Ruby shows the file name, the line number and an excerpt of the code.
Which Ruby do these lessons use?
The code samples in this course were checked with Ruby 4.0.9. A few output formats differ between releases: for example Hash#inspect prints {name: "Aye"} from Ruby 3.4 on, while older versions print {:name=>"Aye"}. When a lesson quotes output or an error message, it came from Ruby 4.0.9; run ruby -v to see which version you have.
- Write code in a .rb file
- ruby reads it, top to bottom
- puts prints results to the terminal
A syntax error stops everything; a runtime error stops at its own line.
General pattern: a Ruby file
# a comment explains the code
def method_name(parameter)
expression_that_becomes_the_result
end
variable = value
puts method_name(variable)A Ruby file is a list of statements that run from top to bottom. def starts a method definition and end closes it. The last expression inside a method is its result, so the return keyword is often left out. A variable appears the moment you assign to it, and no type is written anywhere.
Your first Ruby program
Read this program before you run it. It defines one method that builds a greeting, stores two numbers in variables and prints three lines. Predict those three lines, then save the file as welcome.rb and run ruby welcome.rb (the Get Started lesson shows how).
# welcome.rb: your first Ruby program
def welcome(name, lessons_left)
"Hi #{name}, #{lessons_left} lessons to go!"
end
total = 34
done = 1
puts welcome("Aye Aye", total - done)
puts "Course progress: #{done * 100 / total}%"
puts "More precisely: #{(done * 100.0 / total).round(1)}%"Code breakdown
- A method definition
def welcome(name, lessons_left)def starts a method called welcome that takes two parameters. No types are written; Ruby checks them only when the method actually runs. Methods get a full lesson later, so for now read it as a named recipe that takes two ingredients.
- An implicit return
"Hi #{name}, #{lessons_left} lessons to go!"This line is the whole body. A method's last expression is the value it returns, so no return is needed. Inside double quotes, #{...} is replaced by the value of the variable or expression.
- Variables without declarations
total = 34Assigning creates the variable. There is no var, let or type name, and total could later hold a different kind of value if you wanted it to.
- Arguments are evaluated first
puts welcome("Aye Aye", total - done)total - done is worked out first and gives 33. welcome then returns a string, and puts prints it followed by a newline.
- Integer division
puts "Course progress: #{done * 100 / total}%"Both numbers are Integers, so / is integer division: 100 / 34 is 2 with the fraction dropped. That is why the line says 2%, not 2.94.
- Forcing a Float
(done * 100.0 / total).round(1)Writing 100.0 makes the arithmetic use Floats, so the result is 2.941..., and round(1) keeps one decimal place to give 2.9.
Hi Aye Aye, 33 lessons to go!
Course progress: 2%
More precisely: 2.9%- Write welcome.rb
- ruby reads the file and checks its syntax
- Lines run from top to bottom
- puts writes each line to the terminal
The syntax is valid
All three lines are printed, then the program ends
The syntax is broken
Nothing runs; the message names the file and line
How this course is organized
The course has 34 lessons in five chapters, and each chapter builds on the one before. Take them in order: iterators and blocks assume that you already know variables, methods, arrays and hashes.
| Chapter | Lessons | What you learn |
|---|---|---|
| Basic | 10 | Setup, syntax, variables, data types, methods, user input, arrays and hashes |
| Intermediate | 5 | if / elsif / else, case, while and until loops, the each iterator, Enumerable and Enumerator |
| Advanced | 14 | Classes and objects, initialize, accessors, inheritance, modules, exceptions, files and JSON, blocks, procs and lambdas, gems and Bundler, Minitest, a mini project |
| Projects | 3 | A command-line task tracker application, built in three parts |
| Exercises | 2 | Two practice sets: fundamentals, and classes with blocks |
How to work through a lesson
Every lesson follows the same order: a plain explanation, a problem, the core concept, the general pattern, a worked example explained line by line, common mistakes, a mini challenge and three quiz questions. This routine suits Ruby well because running a file takes only a moment.
1. Predict
Before running an example, write down the output you expect on paper.
2. Run
Run it with ruby in a terminal, or type it into irb line by line, then compare the result with your guess.
3. Break it on purpose
Delete a quote or remove an end, then read the error message from its first line.
4. Do the challenge
Fill in the TODOs in the starter code yourself before you open the solution.
In real projects
Ruby in real projects
The most visible use of Ruby is web applications: Rails powers sites such as GitHub and Shopify, and many Ruby jobs involve maintaining or extending a Rails codebase. That is why the Advanced chapter teaches classes, modules and blocks, the three ideas Rails leans on most.
Ruby is just as common for the small jobs around software: a script that renames a folder of files, a command-line tool that reads a JSON file, a build task, a test suite. Homebrew, the Jekyll site generator and the RSpec and Minitest testing libraries are written in Ruby. The skills you practise here, reading output, running a file and writing a short method, are the ones you use in all of them.
Common mistakes
Common beginner mistakes
1. Starting Rails before Ruby
Rails tutorials assume you can already read Ruby. If you cannot tell a method call from a variable, or a symbol from a string, error messages are baffling because you cannot tell whether the mistake is in Ruby or in the framework. Spend your first weeks on plain .rb files run with the ruby command; the Rails code you meet later will then be mostly familiar.
2. Reading examples without running them
Ruby is quick to try, so reading an example without running it throws away the best part of the language. Type the code out instead of pasting it, guess the output first, then compare. The gap between your guess and the real output is where the learning happens.
3. Expecting indentation or semicolons to matter
Coming from Python or C, people sometimes expect Ruby to care about indentation or semicolons. It cares about neither: a statement ends at the end of the line, and blocks are closed by the end keyword. Forget one and you get an error such as expected an `end` to close the `def` statement, which points at the place where the unfinished method began.
Best practices
Best practices
- Keep one folder for the course with one file per lesson, so you can look back at your own work.
- Re-run your code after every small change, so you always know which change altered the output.
- Use irb for a one-line experiment instead of creating a new file for it.
Mini challenge
Mini challenge: a progress line
Write a method progress_line that takes the number of finished lessons and the total, and returns text such as 6/34 lessons done (17.6%). The percentage must be a Float rounded to one decimal place. Then call it three times and print the results.
- Define progress_line(done, total) and return the text instead of printing it
- Calculate the percentage as a Float (done * 100.0 / total) and round it to 1 decimal place
- When total is 0, show 0.0% instead of dividing by zero
- Print the results for (6, 34), (34, 34) and (0, 0), and predict the output before running
# progress.rb
def progress_line(done, total)
# TODO: when total is zero the percentage is 0.0
# TODO: otherwise work out done * 100.0 / total and round it to 1 decimal
# TODO: return text such as "6/34 lessons done (17.6%)"
end
# TODO: print the progress line for 6 of 34, 34 of 34 and 0 of 0Expected: The program prints these three lines: 6/34 lessons done (17.6%) 34/34 lessons done (100.0%) 0/0 lessons done (0.0%)
Show hint
Test for zero with total.zero?: percent = total.zero? ? 0.0 : (done * 100.0 / total).round(1). Without the guard, 0 * 100.0 / 0 gives NaN in Ruby rather than an error, so the text would end in NaN%. The calculation starts from 100.0, not 100, so that / does not drop the fraction.
Show solution
def progress_line(done, total)
percent = total.zero? ? 0.0 : (done * 100.0 / total).round(1)
"#{done}/#{total} lessons done (#{percent}%)"
end
puts progress_line(6, 34)
puts progress_line(34, 34)
puts progress_line(0, 0)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Ruby is an interpreted, dynamically typed, object-oriented language designed to be pleasant to read and write, used for web apps, scripts and tools
- Write a program in a .rb file, run it with ruby and read the output; if the syntax is broken nothing runs
- A method's last expression is its result, and when both numbers are Integers, / drops the fraction
- Work through the 34 lessons in order, Basic, Intermediate, Advanced, Projects, Exercises, and predict, run, break and challenge in each one
Ruby 4.0 Release — Ruby