Search code examples
rubymethods

What are empty-body methods used for in Ruby?


Currently reading a Ruby style guide and I came across an example:

def no_op; end

What is the purpose of empty body methods?


Solution

  • There are a number of reasons you might create an empty method:

    • Stub a method that you will fill in later.
    • Stub a method that a descendant class will override.
    • Ensure a class or object will #respond_to? a method without necessarily doing anything other than returning nil.
    • Undefine an inherited method's behavior while still allowing it to #respond_to? the message, as opposed to using undef foo on public methods and surprising callers.

    There are possibly other reasons, too, but those are the ones that leapt to mind. Your mileage may vary.