When I came to static typing such as Scala and dart and touched Ruby for the first time in a while, dynamic typing was difficult. It seems that static typing will be officially introduced from Ruby3, but until then, it is better to surpass it with Sorbet.
Sorbet A gem that does static type checking that can also be used in Ruby2 series. Its strength is that it can be gradually introduced into existing projects.
Install
Gemfile
gem 'sorbet', :group => :development
gem 'sorbet-runtime'
bundle install
srb init
srb tc
If you initialize it with srb init
, you can use srb related functions.
srb tc
will type-check the srb-enabled ones described below and give an error.
Use
# typed: true
require 'sorbet-runtime'
module A extend T::Sig
sig {params(left: Float, right: Float).returns(Float)}
def div(left, right)
return left / right;
end
module_function :div
end
puts A.div(1.0, 2.0)
First of all, the ones that pass the type check.
The first line is the valid / invalid control of type check, which must be specified explicitly. If you want to explicitly go over there, you can specify false.
The T :: Sig
on the 4th line is included in the sorbet-runtime
, but by extending this, you can use the sig
that describes the IF of the function parameter.
The official top-level method of ʻextends T :: Sig` also works as a syntax, but it doesn't work with bug. So let module or class extend.
By the way, if you don't describe the IF of the method, you only need to describe it on the first line.
For example, if you return a String type in the above div, an error like this will appear.
lib/main.rb:7: Returning value that does not conform to method result type https://srb.help/7005
7 | return "";
^^^^^^^^^
Expected Float
lib/main.rb:6: Method div has return type Float
6 | def div(left, right)
^^^^^^^^^^^^^^^^^^^^
Got String("") originating from:
lib/main.rb:7:
7 | return "";
However, there are some things that you do not know until runtime if it is something like Integer for Float.
$ srb tc
No errors! Great job.
$ ruby lib/main.rb
Traceback (most recent call last):
...
Expected type Float, got type Integer with value 1 (TypeError)
Caller: lib/main.rb:12
Definition: lib/main.rb:6
IDE Support For vscode, just enter sorbet-lsp. Most vscode plugins themselves are still under development and unstable, but they are useful enough.
Recommended Posts