liveBook · Manning

Type signature

As explained in The Well-Grounded Rubyist, Fourth Edition

A method signature specifies the valid calling form of a method, including its parameters.

A method signature defines the valid calling form of a Ruby method: which arguments it accepts, how they bind to parameters, and which values are optional. section 2.4.1

Ruby signatures can express several argument shapes:

  • Required positional parameters demand exactly one argument each; supplying too many or too few raises ArgumentError. section 2.4.1
  • A splat parameter such as *args accepts zero or more additional arguments and binds them as an array. section 2.4.1
  • Default values make positional parameters optional while allowing a supplied argument to override the default. section 2.4.1
  • Keyword parameters use names at the call site; required keywords must be supplied, while defaults make keywords optional. section 9.3.8
  • Double-splat parameters such as **options collect undeclared keyword arguments into a hash; signatures may also bind a code block with &block. section 9.3.8

Required, catch-all, and default arguments

def two_or_more(a, b, *c) p a, b, c end two_or_more(1, 2, 3, 4) # 1 # 2 # [3, 4] def default_args(a, b, c = 1) p a, b, c end default_args(3, 2) # 3 # 2 # 1 section 2.4.1

Signatures also matter when intercepting unknown messages. An overridden method_missing receives the missing method name first and uses *args for the remaining arguments; the method name arrives as a symbol. section 4.3

>> def m(a:, b:)
>>   p a,b
>> end
=> :m
>> m(a: 1, b: 2)
1
2
=> [1, 2]

Inspect a minimal keyword-argument signature and its matching call. section 9.3.8

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains argument binding through runnable examples, including splats, defaults, keywords, method_missing, and complex combinations.
Examples
Uses irb calls demonstrating arity errors, splat arrays, default values, required keywords, keyword defaults, and keyword collection.
What it assumes
Assumes basic Ruby methods and calls while introducing required, optional, splat, keyword, double-splat, and block parameters.
What you can do after
Apply it via Ruby method definitions and irb to design calls, interpret argument errors, and implement flexible message handlers.
How it connects
Connects method signatures with arguments, keyword arguments, hashes, blocks, method_missing, symbols, and method lookup.

Also explained in

Compare how 8 books explain type signature →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.