liveBook · Manning

Default receiver

As explained in The Well-Grounded Rubyist, Fourth Edition

A default receiver is the implicit object to which a Ruby method call is sent when no receiver is written.

A default receiver is the implicit object that receives a Ruby method call when no receiver and dot are written. The full form, such as obj.talk, becomes a bare call such as talk when self is the intended receiver. section 5.1.4

Ruby resolves a dotless call according to the current execution context:

  • Inside a class-definition block, self is the class object, so no_dot means self.no_dot and can call a class method on that class. section 5.1.4
  • Inside an instance method, self is the object on which that method was called, so x inside y sends the message to the same object. section 5.1.4 section 5.1.3
  • Outside the relevant context, specify the receiver explicitly; C.no_dot is needed once C is no longer self. section 5.1.4
  • Avoid giving a local variable and method the same name: the bare identifier resolves to the variable, while self.talk or talk() forces a method call. section 5.1.4

Calling a method without a receiver

class C def C.no_dot puts "As long as self is C, you can call this method with no dot" end no_dot end C.no_dot The first call works because self is C inside the class body, making no_dot equivalent to self.no_dot. The later call names C explicitly because the surrounding self has changed. section 5.1.4

Implicit self in an instance method

class C def x puts "This is method 'x'" end def y puts "This is method 'y', about to call x without a dot." x end end c = C.new c.y Calling c.y makes c the self inside y, so x is shorthand for self.x and invokes x on c. section 5.1.4

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains receiver omission, self-dependent resolution, explicit qualification, and local-variable ambiguity through runnable examples.
Examples
Uses class methods, nested instance calls, accessor-based name composition, and variable-method name collisions.
What you can do after
Apply implicit self in Ruby methods and distinguish bare method calls from local-variable references.
How it connects
Connects self with receivers, method calls, instance methods, class methods, local variables, and name resolution.

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.