Send Me a River (Ruby Send Method)

akpojotor shemi
3 min readDec 17, 2019

--

This blog covers

send method introduction and dot notation

use of send with custom methods

use of send with mass assignment

use send with private methods

Send method basics

Everything in Ruby is an object. Typically dot notation is used to a call method on an object. In the code snippet just below, on line 2 the + method is called on the integer object. The send method works similarly to dot notation.

The send method invokes the method identified by symbol, passing it any arguments specified.When the method is identified by a string, the string is converted to a symbol.

In principle, any method can be sent to an object. However response is not guaranteed (at least not without errors). Each object has a number of acceptable associated methods. Calling “methods” method on the integer object will show a list of methods associated with that object.

code snippet basic send and dot notation
output: call methods on an integer object

Let’s demo a few methods from the output above. For example, a few selected methods are called on the integer object as shown in the snippet below.

Still not sure what method to send to an object? call the respond_to? method on the object to find out. In example below the ‘hail mary’ method returned false, everything else returned true. ‘hail mary’ method returned false because it is neither an integer object method or a custom-made method.

Send with Custom Methods

Beyond the associated methods available with an object, we can create custom-made methods. In the contrived example below, song_title method concatenates individual words and returns the merged string.

Send with Mass Assignments

Send method also comes in handy in mass assignments. In the example below the Person class can be instantiated with unspecific number of attributes. These attributes are passed in as a hash argument. The ruby send method then calls the method name that is the key’s name, with an argument of the value. Notice that james and paul instances of the Person class were instantiated using different hash with slightly keys/attributes.The fact that we can dynamically instantiate the class with varying number of keys/attributes with making huge changes to the code, highlights the benefit of the using the send method.

Use Send to call Private Methods

Ideally, private methods should be accessed internally within a class and not outside the class. We have seen how the send method can call on private method but it can also call public methods. The *public_send* method like the send method invokes the method identified by symbol, passing it any arguments specified. However, unlike send, public_send calls public methods only.

Summary

This article reviewed the send method, how to use respond_to? to check which method to call on an object, how to access private method, how to use send with mass assignments.

--

--