liveBook · Manning

Dotted notation

As explained in The Well-Grounded Rubyist, Fourth Edition

The dot operator is Ruby syntax that sends the expression on its right as a message to the object on its left.

In `x = "100".to_i`, the dot sends `to_i` to the string `"100"`. The string is the receiver; the method’s result, integer `100`, is assigned to `x`. Ruby uses this syntax for objects represented by literals as well as variables. section 1.1.4

The dot is Ruby’s message-sending operator: the object on its left receives the message named on its right. Sending a message usually calls a method of that name. The distinction matters because a receiver might not have a matching method. Ruby can handle an unknown message through `method_missing`; the dot alone does not guarantee that a method exists. section 1.1.4 section 2.1.2

Give an object a message to answer

Create an object with `obj = Object.new`, define `def obj.talk; puts "I am an object."; end`, then call `obj.talk`. Here `obj` is the receiver and `talk` names the method it responds to. An argument-bearing call uses the same relationship: `"100".to_i(9)` sends `to_i` to the string with `9` as an argument. section 2.1.2 section 1.1.4

A method call need not show a dot. When the receiver is `self`, Ruby can use it implicitly: inside one instance method, `x` can call another method on the same object. Outside that context, an explicit receiver such as `C.no_dot` may be needed. If a local variable and method share a name, the bare name selects the variable; use `self.talk` or `talk()` to specify the method. section 5.1.4

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains receivers, method calls, arguments, and implicit `self`, while deferring detailed treatment of `method_missing`.
Examples
Demonstrates string conversion, an `Object.new` receiver with a `talk` method, and calls with and without an explicit receiver.
What it assumes
Assumes familiarity with variables and expressions while introducing receivers and message sending through small Ruby examples.
What you can do after
Practice/perform Ruby method calls with explicit or implicit receivers and distinguish a bare method call from a same-named local variable.
How it connects
Connects dotted notation to objects, message sending, methods, `self`, local variables, and `method_missing`.

Also explained in

Compare how 9 books explain dotted notation →

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.