Ruby Basics : Sending a Message to a Receiver

In this article, you will learn about the receiver object and sending messages to a receiver.

Hail Taxi

Let's write a simple program to hail a taxi.

3.times do 
  puts 'Taxi'
end

This prints:

Taxi
Taxi
Taxi

Hail Taxi

Receiver and Message

Let's identify the receiver and the message in this simple program. The number 3 is the receiver. The times() method is the message. The dot represents sending the message to the receiver.

Receiver, Message and Sending a Message

The dot notation is used when sending a message is explicit.

Receiver Object

The receiver is an object. Let's find out the class of the receiver object for our simple program.

puts 3.class

This prints:

Fixnum

This demonstrates that Fixnum object 3 is the receiver object. It receives the times() message.

Fixnum Receiver Object

Fabio Asks

Why is it called the receiver?

Because this object would have received the message that caused the method to execute.

Rhonda Asks

Why do we need a receiver?

In a OO language like Ruby, everything happens by sending messages to an object. This object is the receiver. In the next chapter, we will discuss more about message passing.

Exercise

Identify the receiver for the car program we wrote in the previous chapter.

Summary

In this article, we saw:

  1. What is a receiver?
  2. What is a message?

In the next article we will answer questions such as, what is a sender? Who is sending this message?


Related Articles