Easily try Ruby 3.0.0 type checking (rbs)

Ruby 3.0.0 has been released, so I tried type checking.

In order to check the type, some preparation is required, so I will introduce an easy method.

** 1. Install Ruby 3.0.0 **

$ rbenv install 3.0.0
$ rbenv local 3.0.0

If you get an error here, you may have to upgrade ruby-build.

reference: rbenv/ruby-build update https://qiita.com/jhanyu/items/38671f7e9f03b77670c0

** 2. Write the desired code **

Let's do a type check on this code. Save it with the file name test.rb.

test.rb


class Test
  def myfunc str
    puts str
  end
end

t = Test.new
t.myfunc("test")

** 3. Export type information **

You can use typeprof to do type inference and write out type information.

typeprof test.rb > test.rbs

The contents of test.rbs are like this.

test.rbs


$ cat test.rbs
# Classes
class Test
  def myfunc: (String str) -> nil
end

This time it was generated by typeprof, but you can also specify the definition for this file yourself.

Please check this out for details. ruby/rbs https://github.com/ruby/rbs

** 4. Prepare a type checker (steep) **

Install the type checker.

Learn why you need to install steep.

A note about the relationship between RBS, TypeProf, Steep, and Sorbet, which are the static analysis functions of Ruby 3. https://techlife.cookpad.com/entry/2020/12/09/120454

$ gem install steep

Initialize steep.

$ steep init

Since Steepfile is created, rewrite it as follows.

Steepfile


target :lib do
  check "."
  signature "."
end

** 5. Type check **

$ steep check

Nothing is displayed. This means that there is no problem.

** 6. Check with a funny mold on purpose **

Rewrite the original code as follows:

test.rb


class Test
  def myfunc str
    puts str
  end
end

t = Test.new
t.myfunc(1) #Use a type that is not a String

I will check it again.

$ steep check
test.rb:8:9: ArgumentTypeMismatch: receiver=::Test, expected=::String, actual=::Integer (1)

I got an error. It feels good ⭐

** At the end **

Note regularly publishes iOS development, especially CoreML, ARKit, Metal, etc. https://note.com/tokyoyoshida

It is also posted on Twitter. https://twitter.com/jugemjugemjugem

** References ** Ruby 3.0.0 release https://www.ruby-lang.org/ja/news/2020/12/25/ruby-3-0-0-released/

Type check with Ruby! Introduction to RBS to understand by moving ~ Understand with sample code! Major new features and changes in Ruby 3.0 Part 1 ~ https://qiita.com/jnchito/items/bf8c6c2e1dd6cff05f4e

Recommended Posts

Easily try Ruby 3.0.0 type checking (rbs)
Chart type Ruby
Try Ruby Minitest
Feel the basic type and reference type easily with ruby
[Ruby] Method to easily get the receiver type .class
Feel the basic type and reference type easily with ruby 2
Variable type in ruby
Try using Cocoa from Ruby
Try functional type in Java! ①
Try using gRPC in Ruby
[Programming Encyclopedia] §2 Try using Ruby
Static analysis is finally coming to Ruby, so I'll give it a try. [RBS] [Type Prof] [Steep]