Skip to content

Latest commit

 

History

History
148 lines (109 loc) · 3.73 KB

quickref.md

File metadata and controls

148 lines (109 loc) · 3.73 KB
id title
quickref
Quick Reference

This guide is a quick reference for people already somewhat familiar with Sorbet. For getting started with Sorbet, see Adopting Sorbet.

Enabling type checking

To enable static checking with srb, add this line (called a sigil) to the top of your Ruby file:

# typed: true

This file will now be checked by Sorbet!

However, not much will really change. Sorbet knows about the types of methods in the standard library, but not methods we've defined ourselves. To teach Sorbet about the types of our methods, we have to add signatures above the method:

# typed: true

# (1) Bring T::Sig into scope:
require 'sorbet-runtime'

class Main
  # (2) extend T::Sig to get access to `sig` for annotations:
  extend T::Sig

  # (3) Add a `sig` annotation above your method:
  sig {params(x: String).returns(Integer)}
  def self.main(x)
    x.length
  end

  # alternatively, for a method with no parameters:
  sig {returns(Integer)}
  def no_params
    42
  end
end

Now srb and sorbet-runtime will check that our Main.main method is given only Strings and returns only Integers:

  • srb will do this with static checks.
  • sorbet-runtime will do this by wrapping Main.main with dynamic checks that run every time the method is called.

Type System

The complete type system reference can be found to the left. Here's a quick table of contents:

How do I...

Figure out what's going on?

There are a number of common strategies that help when tracking down confusing behavior in Sorbet:

Troubleshooting

Run Sorbet on a small example?

The easiest way to try out Sorbet on small examples is to use sorbet.run, which runs sorbet (the static component) in your browser.

→ sorbet.run

Run Sorbet on a small file?

Consider this file:

# -- foo.rb --
# typed: true
require 'sorbet-runtime'

class Main
  extend T::Sig

  sig {void}
  def self.main
    puts 'Hello, world!'
  end
end

Main.main

To check it statically:

❯ srb tc foo.rb

Note: If there's a sorbet/config file in the current directory, this command will potentially run on more than just this single file. Run srb tc from a different folder to check a single file in isolation.

To test out how the runtime checks work:

❯ bundle exec ruby foo.rb

Note that foo.rb can only reference constants in the file and the standard library.

Run Sorbet on a whole project?

Each Sorbet project should have a sorbet/config file at the root of the project, which describes how to typecheck the project. If we are at the root of our project, we can check the whole project with:

❯ srb

For more information, see Adopting Sorbet.