LoginSignup
1
0

More than 3 years have passed since last update.

Ruby + RBS + steep で再帰型を定義する

Posted at

目的

jsonのような、Hash型がHashを持っているような場合にどう記述するか?という問題です。

環境

$ ruby --version
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux]
$ rbs --version
rbs 1.0.3
$ steep --version
0.39.0

対象のコード

以下のような、入力次第ではいくらでも深く出来るような実装を考えます。C.rec の返値の型には何を指定すれば良いのでしょうか?

module C
  def self.rec
    str = gets
    return nil if str.nil?

    { val: str.chomp, next: rec }
  end
end

p C.rec
$ ruby lib/test.rb 
a
g
c
{:val=>"a", :next=>{:val=>"g", :next=>{:val=>"c", :next=>nil}}}

解決策

type エイリアスを使う。エイリアス自身を含む型も定義できるようです。

type jhash = Hash[Symbol, String | nil | jhash]

module C
  def self.rec: () -> jhash?
end

steep チェックも問題なく通ります。

$ steep check
1
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
1
0