rubyoopduck-typing

How do Ruby programmers do type checking?


Since there is no type in ruby, how do Ruby programmers make sure a function receives correct arguments? Right now, I am repeating if object.kind_of/instance_of statements to check and raise runtime errors everywhere, which is ugly. There must be a better way of doing this.


Solution

  • Ruby is, of course, dynamically typed.

    Thus the method documentation determines the type contract; the type-information is moved from the formal type-system to the [informal type specification in the] method documentation. I mix generalities like "acts like an array" and specifics such as "is a string". The caller should only expect to work with the stated types.

    If the caller violates this contract then anything can happen. The method need not worry: it was used incorrectly.

    In light of the above, I avoid checking for a specific type and avoid trying to create overloads with such behavior.

    Unit-tests can help ensure that the contract works for expected data.