Skip to content
Tutorials Center
My learning

Topics

Lesson 129 of 134 ยท Practice

Ruby Cheat Sheet

A Ruby 4.0 cheat sheet with runnable examples for variables, strings, collections, blocks, classes, pattern matching and errors.

This page is a quick reference you can keep open while you write Ruby. Every section is short on purpose: a few lines that remind you of the shape of the syntax, with a runnable example you can edit. When you need the full story, each section links to the lesson that explains it properly.

Everything here is modern Ruby (3.4 and 4.0). You will see it as the implicit block parameter, endless methods, Data.define, pattern matching and hash shorthand. Where an older style still matters because you will meet it in real code, the cheat sheet says so.

Output, variables and constants

puts prints a value followed by a newline, print prints without one, and p prints the inspect form and returns its argument, which makes it the best debugging tool. Local variables start with a lowercase letter, constants with an uppercase one, instance variables with @, and globals with $. See Your First Ruby Program and Variables and Constants.

Ruby Output and variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Types and conversions

Everything is an object. The core types are Integer, Float, String, Symbol, Array, Hash, Range, NilClass, TrueClass and FalseClass. Only nil and false are falsy: 0, "" and [] are all truthy. Convert explicitly with to_i, to_f, to_s, to_sym, to_a, or use the strict Integer("42") and Float("1.5"), which raise on bad input. See Basic Types and Numbers.

Ruby Types and conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Strings and symbols

Double quotes interpolate #{} and process escapes; single quotes do neither. Strings are mutable, and many methods come in a safe form (upcase) and a mutating bang form (upcase!). Slices use [start, length] or ranges. Heredocs with <<~ strip the common indentation. See Strings, String Methods and Symbols.

Ruby String toolbox

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Arrays and hashes

Arrays are ordered and indexed from zero; negative indexes count from the end. Hashes keep insertion order and are usually keyed by symbols. dig and fetch read nested or required keys safely. See Arrays and Hashes.

Ruby Array and hash essentials

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Iterating and transforming

Ruby programmers rarely write index loops. each visits items, map transforms, select and reject filter, reduce folds, group_by, partition, tally and each_with_object summarize. it is the implicit single block parameter. See Iterating and Transforming Arrays and The Enumerable Module.

Ruby Enumerable at a glance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Control flow

if, unless, case and while are expressions that return a value. Modifier forms (puts "x" if ok) suit one-liners. case uses ===, so it matches ranges, classes, regexes and lambdas. See if, elsif, else and unless, case and when and Loops.

Ruby Control flow cheat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Methods and blocks

Methods return the value of their last expression. Arguments can be positional, optional, splat (*args), keyword (key:), double splat (**opts) and a block (&blk). yield calls the block. Lambdas check their argument count and return from themselves; procs do not. See Methods, Method Arguments, Blocks and Procs and Lambdas.

Ruby Method argument kinds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Classes, modules and structs

A class bundles state and behavior. attr_reader, attr_writer and attr_accessor generate accessors. Modules share behavior with include (instance methods), extend (singleton methods) or prepend (before the class). Struct and Data.define create small value classes; Data is immutable. See Classes and Objects, Modules and Mixins and Struct and Data.

Ruby Classes, modules, Struct and Data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Pattern matching

case/in destructures arrays, hashes and objects that define deconstruct or deconstruct_keys. => raises if the pattern does not match; in returns true or false. A guard adds if, and ^ pins an existing value. See Pattern Matching.

Ruby Pattern matching cheat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Exceptions

begin/rescue/else/ensure/end handles errors; a def body or a do block can carry rescue directly. Rescue StandardError (the default), never Exception. raise with no argument re-raises, retry restarts the begin, and cause records the original error. See Exceptions and Custom Exceptions.

Ruby Exception cheat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Quick lookup table

Need Write
Swap two variables a, b = b, a
Default for nil value ||= 10
Is it a type x.is_a?(Integer), Integer === x
Safe call user&.name
Range 1..5 (inclusive), 1...5 (exclusive), 1.. (endless)
Word array %w[a b c], symbols %i[a b c]
Format number format("%.2f", x), x.round(2)
Read a line gets&.chomp
Frozen value "abc".freeze, CONST = [...].freeze
Object copy dup (shallow), clone (keeps frozen state)
Call by name obj.send(:name, arg), obj.public_send(...)
Check method obj.respond_to?(:name)
Method list Obj.instance_methods(false)
Chain results value.then { transform(it) }, tap { p it }

When you forget a method name, ask Ruby. Array.instance_methods(false).sort lists what Array defines itself, 5.method(:+).owner tells you where a method comes from, and obj.methods - Object.instance_methods shows only the interesting ones.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which values are falsy in Ruby?

    Only nil and false are falsy. Zero, the empty string and empty arrays are all truthy, which surprises people coming from Python or JavaScript.
  2. 2. What does p return?

    p prints the inspect form and returns its argument, so you can drop it into the middle of an expression while debugging.
  3. 3. Which line creates an immutable value object with named fields?

    Data.define builds a class whose instances cannot be modified; Struct instances are mutable by default.
  4. 4. What is the safest way to read a required key from a hash?

    fetch raises KeyError when the key is missing, so a typo fails loudly instead of silently producing nil.
  5. 5. What does case use to compare the value with each when?

    case calls pattern === value. That is why classes, ranges, regexes and lambdas all work as when conditions.

Summary

  • puts prints, p inspects and returns its argument, print skips the newline.
  • Only nil and false are falsy; everything else, including 0 and "", is truthy.
  • Use fetch for required hash keys, dig for nested ones and &. for nil-safe calls.
  • Prefer map, select, reduce, group_by and tally over index loops; it is the implicit block parameter.
  • case and when use ===; case/in destructures arrays, hashes and objects.
  • Methods accept positional, optional, splat, keyword, double splat and block arguments; ... forwards all of them.
  • Struct is a mutable record, Data.define an immutable one.
  • Rescue StandardError subclasses, re-raise with raise, and keep the original in cause.

Next: Common Ruby Mistakes