Introduce defp keyword for defining overloadable, pattern matched methods
Ruby developer Zeke Gabrielse proposes the introduction of a new keyword, defp, in Ruby to define methods that apply pattern matching to their arguments. This feature aims to improve code quality and make the developer's intent clearer by refactoring complex methods that use case statements for handling varied arguments.
The proposed defp keyword would allow developers to define smaller, simpler methods that handle specific argument patterns, bringing method overloads to Ruby. Additionally, this feature adds a way to define more typing to the language, similar to what RBS has attempted but in a more Ruby-like way.
The idea of automatic dispatching without boilerplate code is appealing, although method overloading has never existed in Ruby. Pattern matching in the method signature, on the other hand, is highly desired by developers.
Zeke's proposal has sparked further discussion within the Ruby community, with many expressing their support for the introduction of the defp keyword.
Original idea by Victor Shepelev: Read more
Further discussion: Read more
def foo(nb => Integer) # class validation
def foo(minutes => 0..59) # range/structure validation
def foo(if: => condition) # alias for keyword argument (#18402)
def foo(v => @hostname) # easy way to set instance variables (#15192 and many others)
The Ruby community eagerly awaits the implementation of this proposed feature, as it has the potential to significantly enhance the language's expressiveness and code maintainability.