Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

RB
Ruby
0/12 completed
Beginner
Hello RubyVariables and typesConditions and loopsMethods
Intermediate
Arrays and hashesBlocks, procs and iteratorsClasses and objectsModules and mixins
Advanced
Exceptions and filesMetaprogramming
Pro
Gems, Bundler and testingRuby on Rails basics
Tracks / Ruby / Beginner

Methods

A method is a named piece of code. Ruby methods are flexible: arguments can have defaults or names, the last expression is returned automatically, and calls look like plain English because parentheses are optional.

Defining methods

Ruby · editable
  • def name(params) … end defines a method.
  • The last expression is returned automatically. You only write return to leave early.
  • Method names use snake_case. Names ending in ? return a boolean; names ending in ! change the object or are "dangerous".
Ruby · editable

Arguments

Defaults

Ruby · editable

Keyword arguments

For anything with more than one or two options, use keyword arguments. They're self-documenting and can be given in any order:

Ruby · editable

name: with no default is required:

Ruby · editable

Any number of arguments

Ruby · editable
Syntax Collects
*args Extra positional arguments, as an array
**opts Extra keyword arguments, as a hash
&block A block passed to the method (next-but-one lesson)

Returning several values

Return an array and destructure it:

Ruby · editable

Scope

Methods can't see variables from outside them. Each method has its own local variables:

Ruby · editable

Pass what a method needs as arguments. (Blocks are different: they can see the variables around them, as you'll see later.)

Objects are passed by reference

Arguments are references to the same object. Calling a method that changes the object is visible outside; reassigning the parameter isn't:

Ruby · editable

Recursion

Ruby · editable

memo[n] ||= … computes a value only the first time and stores it (memoisation), which turns an exponentially slow function into a fast one.

Method objects and method_missing, briefly

Methods are objects you can pass around:

Ruby · editable

That flexibility is the base of Ruby's metaprogramming, covered in its own lesson.

Practice

  1. Write def bmi(weight_kg, height_m) that returns the BMI rounded to 1 decimal.
  2. Write def format_price(cents, currency: "₹") that returns strings like ₹19.99.
  3. Write def average(*numbers) that returns 0 when given no numbers.
  4. Write def palindrome?(text) that ignores case and spaces.
✎ Check your understanding

1.What does a Ruby method return if there's no return statement?

2.Which call matches def ship(order, express: false)?

3.Inside a method, can you use a local variable defined outside it?

4.What does def collect(*items) do with collect(1, 2, 3)?

← Conditions and loops