8
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ruby 3.0.0の型チェック(rbs)を簡単に試す

Last updated at Posted at 2020-12-25

Ruby 3.0.0がリリースされたので、型チェックを試してみました。

型チェックをするためには、少し準備が必要だったりするので簡単にできる方法を紹介します。

1.Ruby 3.0.0をインストールする

$ rbenv install 3.0.0
$ rbenv local 3.0.0

ここでエラーが出る場合は、ruby-buildをアップグレードしないといけないかもしれません。

参考:
rbenv/ruby-buildのアップデート
https://qiita.com/jhanyu/items/38671f7e9f03b77670c0

2.目的のコードを書く

このコードを対象に型チェックをしてみます。
test.rbというファイル名で保存します。

test.rb
class Test
  def myfunc str
    puts str
  end
end

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

3.型情報を書き出す

typeprofを使うと、型推論をして型情報を書き出してくれます。

typeprof test.rb > test.rbs

test.rbsの中身はこんな感じです。

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

今回はtypeprofで生成しましたが、このファイルは自分で定義を指定することもできます。

詳しくはこちらをご覧ください。
ruby/rbs
https://github.com/ruby/rbs

4.型チェッカー(steep)を準備する

型チェッカーをインストールします。

なぜsteepをインストールする必要があるのかについてはこちらをご覧ください。

Ruby 3の静的解析機能のRBS、TypeProf、Steep、Sorbetの関係についてのノート
https://techlife.cookpad.com/entry/2020/12/09/120454

$ gem install steep

steepの初期化をします。

$ steep init

Steepfileが出来るのでこれを次のように書き換えます。

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

5.型チェックをする

$ steep check

何も表示されません。これは問題がないということです。

6.わざとおかしい型を使ってチェックしてみる

元のコードを次のように書き換えます。

test.rb
class Test
  def myfunc str
    puts str
  end
end

t = Test.new
t.myfunc(1) # わざStringではない型を使う

あらためてチェックします。

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

エラーが出ました。
いい感じですね⭐

終わりに

NoteではiOS開発、とくにCoreML、ARKit、Metalなどについて定期的に発信しています。
https://note.com/tokyoyoshida

Twitterでも発信しています。
https://twitter.com/jugemjugemjugem

参考資料
Ruby 3.0.0 リリース
https://www.ruby-lang.org/ja/news/2020/12/25/ruby-3-0-0-released/

Rubyで型チェック!動かして理解するRBS入門 〜サンプルコードでわかる!Ruby 3.0の主な新機能と変更点 Part 1〜
https://qiita.com/jnchito/items/bf8c6c2e1dd6cff05f4e

8
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?