liveBook · Manning

Message

As explained in The Well-Grounded Rubyist, Fourth Edition

Message sending is the process of requesting behavior from a Ruby object by sending it a message.

A message to a string

In `x = "100".to_i`, the string is the receiver. The dot sends it the message `to_i`; the matching method runs, and its result, the integer `100`, is assigned to `x`. section 1.1.4

Ruby values are objects. To request behavior from one, put a message to the right of a dot and the receiving object to the left. The receiver may be a literal, such as `"100"`, or an object represented by a variable. A message usually matches a method name, so “sending a message” and “calling a method” often describe the same operation. section 1.1.4 section 2.1.2

Teaching an object to respond

Create an object with `obj = Object.new`, define `def obj.talk` to print two lines, and then send `obj.talk`. The object responds to `talk` because it has a method with that name. Message sending is how code requests an action from an object, including behavior you define yourself. section 2.1.2

The two terms are not quite interchangeable: a receiver may have no method matching a message. Ruby can route an unknown message through `method_missing` rather than simply execute a matching method. Calls may also pass arguments, as in `"100".to_i(9)`. A call without an explicit receiver, such as `puts "Hello"`, sends its message to `self`. section 1.1.4 section 1.5

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains receivers, dot syntax, method matching, arguments and unknown-message handling; defers detailed treatment of `method_missing`.
Examples
Uses string conversion with `"100".to_i`, a defined `talk` method and the bareword call `puts "Hello"`.
What it assumes
Starts with basic Ruby expressions while introducing objects, receivers and method definition through small runnable examples.
What you can do after
Apply it via Ruby’s dot syntax to request behavior from objects and define a method an object can respond to.
How it connects
Connects message sending to objects, methods, receivers, arguments, `self` and `method_missing`.

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.