Skip to content
Tutorials Center
My learning

Topics

Lesson 112 of 134 ยท Testing and Tooling

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.

Ruby is dynamically typed: a variable can hold anything, and a wrong argument is only noticed when the line runs. That freedom is part of why Ruby code is short and pleasant, but in a large codebase it also means that renaming a method or changing a return value can break a caller nobody remembered. Gradual typing is the compromise. You keep writing normal Ruby, and you add type information only where it pays off, in files or methods you choose. A separate tool reads that information and reports mismatches before the program runs.

Ruby has two main systems for this. RBS is the official signature language that ships with Ruby, and Steep is a type checker that uses it. Sorbet is a different system, built at Stripe, that puts signatures inside the Ruby source. Neither changes how your program runs. Because third-party checkers are not installed on our runner, Steep and Sorbet appear as read-only snippets here, but the rbs library is bundled with Ruby, so we can parse real signatures and even build a small checker on top of them.

The idea of gradual typing

A type checker does not run your program. It reads the code and the declared types, then reasons about every path: "this method promises a String, but this branch returns nil." The word gradual means that anything without a signature is treated as untyped, a value that matches every type, so the checker never complains about code it knows nothing about. You can start with one class and grow from there.

flowchart LR
  src["Ruby source<br/>(user.rb)"] --> steep["Steep"]
  rbs["RBS signatures<br/>(user.rbs)"] --> steep
  steep --> report["Type errors<br/>before you run"]
  src --> run["ruby user.rb"]
  run --> out["Normal program output"]

With RBS, signatures live in separate files; the checker reads both, while Ruby itself only ever sees the source.

Types are not a substitute for tests. A type says "this is an Integer"; only a test can say "this is the right integer." Many teams use both: types to catch typos, nil mistakes and broken call sites, and tests for behavior.

RBS: the signature language

An RBS file describes the shape of your code. It uses a syntax close to Ruby but contains no method bodies.

Ruby
# sig/shop.rbs
class Item
  attr_reader name: String
  attr_reader price_cents: Integer

  def initialize: (name: String, price_cents: Integer) -> void
  def price: () -> Float
  def label: (?upcase: bool) -> String
end

class Cart
  def initialize: () -> void
  def add: (Item item, ?Integer quantity) -> self
  def total_cents: () -> Integer
  def find: (String name) -> Item?
  def names: () -> Array[String]
end

Read a signature from left to right: the parameters in parentheses, then ->, then the return type. A few pieces of vocabulary cover most files:

RBS Meaning
String, Integer, Item An instance of that class
Item? Either an Item or nil (optional)
Integer | String A union: either type
Array[String], Hash[Symbol, Integer] Generic collections with element types
?Integer quantity An optional positional parameter
name: String / ?upcase: bool A required / optional keyword parameter
bool true or false
void The return value is not meant to be used
self Returns the same type as the receiver
untyped Escape hatch: matches anything

You can also declare modules, interfaces (a set of method names without a class), type aliases such as type id = Integer | String, and generics like class Box[T]. Ruby ships signatures for the core classes and the standard library, so Array, String and friends already have types.

Parsing RBS with the rbs library

The rbs gem is a bundled gem, so require "rbs" works here. It parses a signature into a tree of objects, which is the same tree that Steep, documentation generators and your own scripts use. This example parses a small file and prints every method with its parameter and return types.

Ruby Reading RBS signatures with the rbs library

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.

RBS::Parser.parse_signature returns the buffer, any directives (such as use lines) and the list of declarations. Each declaration (class, module, interface, alias) holds members, and a method member holds one or more overloads, because a method may accept several shapes of arguments. The same API powers rbs validate and tools that generate documentation.

A runtime checker built on RBS

Static checkers are complicated, but the idea is simple enough to build a toy version. The following module reads a signature and wraps a method with prepend, so each call is checked against its declared types and an error is raised at the call site. It supports plain classes, optionals (Integer?), unions and bool. This is how runtime-checking libraries work, and it makes the types concrete.

Ruby A tiny runtime checker driven by RBS

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.

The pattern is the one from the prepend memoize example: a prepended module runs first, does its check, then calls super for the real method. A static checker does the same reasoning but earlier, without running anything, and across all code paths at once. The runtime version only catches what a particular run happens to execute.

Steep: checking Ruby against RBS

Steep reads your Ruby files and your .rbs signatures and reports disagreements. You install it with gem install steep (or add it to your Gemfile), generate a configuration with steep init, and run steep check. The configuration is a Steepfile:

Ruby
# Steepfile
target :app do
  signature "sig"
  check "lib"

  library "json", "time"   # use the stdlib signatures that ship with RBS
end

Given the Cart signature above and this implementation:

Ruby
class Cart
  def find(name)
    @items.find { |item| item.name == name }
  end

  def total_cents
    @items.sum(&:price_cents).to_s   # returns a String, not an Integer
  end
end

steep check reports something like "the method total_cents returns String, but Integer is declared," and it flags uses of the result of find that forget the nil case, such as cart.find("pen").price. That nil check is the biggest practical win: the classic "undefined method for nil" error is caught before shipping.

Signatures can be written by hand, generated as a first draft with rbs prototype rb lib/cart.rb, or written as comments next to the code with the rbs-inline tool (# @rbs name: String), which keeps types and implementation in one file. The rbs collection command installs signatures for gems that publish them.

Sorbet: signatures inside the source

Sorbet takes the opposite approach. Signatures are Ruby code, written with sig blocks from the sorbet-runtime gem. The static checker is a fast command-line tool, srb tc, and the same sig blocks are also checked while the program runs.

Ruby
# typed: strict
require "sorbet-runtime"

class Cart
  extend T::Sig

  sig { params(name: String, quantity: Integer).returns(T::Array[String]) }
  def add(name, quantity = 1)
    Array.new(quantity, name)
  end

  sig { params(name: String).returns(T.nilable(Integer)) }
  def find(name)
    @stock[name]
  end
end

The first line, # typed: strict, sets how strict the checker is for this file; levels run from ignore and false (only syntax and constant errors) through true and strict to strong. That is gradual typing in action: you can raise the level one file at a time. Sorbet writes its types with T.nilable(X), T.any(A, B), T::Array[X] and T.untyped, which correspond to RBS X?, A | B, Array[X] and untyped. Methods such as T.let and T.must assert types inline.

RBS and Steep or Sorbet: which one?

RBS + Steep Sorbet
Signature location Separate .rbs files (or rbs-inline comments) sig blocks in the source
Maintained by The Ruby core team and community Stripe and contributors
Runtime effect None Optional runtime checks via sorbet-runtime
Speed Fine for most projects Very fast, built for huge monorepos
Gem signatures rbs collection tapioca generates RBI files

Both are legitimate choices, and which one fits depends on the team. RBS is the standard, so editors and tools such as documentation generators understand it. Sorbet's runtime checks and speed suit very large codebases. Whichever you pick, start small: type your core domain classes, mark the rest untyped, wire the checker into CI, and tighten it over time. Types also help the documentation and tooling around your code because they describe each method's contract in a machine-readable form.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the word gradual mean in gradual typing?

    Untyped code matches every type, so the checker stays quiet about what it cannot see. That lets you adopt types incrementally.
  2. 2. In RBS, what does def find: (String name) -> Item? declare?

    The question mark after a type means optional: the value may be nil. Steep then forces callers to handle the nil case.
  3. 3. Where do Sorbet signatures live, compared with RBS?

    Sorbet signatures are Ruby code (sig { ... }), while RBS keeps them in separate .rbs files or rbs-inline comments.
  4. 4. Why can a static checker catch a bug that a runtime check misses?

    A runtime check only sees the values from one particular run. A static checker analyzes every branch in advance.

Summary

  • Gradual typing adds optional type information to Ruby; code without signatures is untyped and never causes errors by itself.
  • RBS is the official signature language: .rbs files describe classes, methods, generics, optionals (X?) and unions (A | B), and Ruby bundles the rbs library to parse them.
  • Steep checks your Ruby against RBS signatures and is especially good at finding unhandled nil.
  • Sorbet keeps signatures in sig blocks, offers strictness levels per file with # typed: and can check types at runtime with sorbet-runtime.
  • Types complement tests; start with core classes, leave the rest untyped, run the checker in CI and tighten gradually.
  • You can build a small runtime checker from the RBS parse tree and prepend, which shows exactly what a signature promises.

Next: Rails Overview