Skip to content

Commit ab28a38

Browse files
committed
Add Method Definitions section
1 parent deaab96 commit ab28a38

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

docs/inline.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,81 @@ This creates the types `::API`, `::API::V1`, and `::API::V1::Resources`.
111111
- Generic module definitions are not supported
112112
- Module self-type constraints are not supported
113113

114+
## Method Definitions
115+
116+
Inline RBS supports methods defined using the `def` syntax in Ruby.
117+
118+
```ruby
119+
class Calculator
120+
def add(x, y) = x+y
121+
end
122+
```
123+
124+
It detects method definitions and allows you to add annotation comments to describe their types.
125+
126+
### Unannotated method definition
127+
128+
Methods defined with `def` syntax are detected, but they are untyped.
129+
130+
```ruby
131+
class Calculator
132+
def add(x, y) = x+y
133+
end
134+
```
135+
136+
The type of the `Calculator#add` method is `(?) -> untyped` -- it accepts any arguments without type checking and returns an `untyped` object.
137+
138+
### Method type annotation syntax
139+
140+
You can define the type of the method using `@rbs` and `:` syntax.
141+
142+
```ruby
143+
class Calculator
144+
# @rbs (Integer, Integer) -> Integer
145+
def add(x, y) = x + y
146+
147+
#: (Integer, Integer) -> Integer
148+
def subtract(x, y) = x - y
149+
end
150+
```
151+
152+
The type of both methods is `(Integer, Integer) -> Integer` -- they take two `Integer` objects and return an `Integer` object.
153+
154+
Both syntaxes support method overloading:
155+
156+
```ruby
157+
class Calculator
158+
# @rbs (Integer, Integer) -> Integer
159+
# | (Float, Float) -> Float
160+
def add(x, y) = x + y
161+
162+
#: (Integer, Integer) -> Integer
163+
#: (Float, Float) -> Float
164+
def subtract(x, y) = x - y
165+
end
166+
```
167+
168+
The type of both methods is `(Integer, Integer) -> Integer | (Float, Float) -> Float`.
169+
170+
> [!NOTE]
171+
> The `@rbs METHOD-TYPE` syntax allows overloads with the `|` operator, just like in RBS files.
172+
> Multiple `: METHOD-TYPE` declarations are required for overloads.
173+
174+
#### Doc-style syntax
175+
176+
The `@rbs return: T` syntax declares the return type of a method:
177+
178+
```ruby
179+
class Calculator
180+
# @rbs return: String
181+
def to_s
182+
"Calculator"
183+
end
184+
end
185+
```
186+
187+
### Current Limitations
188+
189+
- Class methods and singleton methods are not supported
190+
- Parameter types are not supported with doc-style syntax
191+
- Method visibility declaration is not supported yet

0 commit comments

Comments
 (0)