1.0 Just what does #send do?

Dynamic method calls

You have just discovered that the staff you have been carrying around your entire life also turns into a glider. But you don't really know how to fly. Fortunately, your previous incarnations speak in your head telling you what to do. You just have to do what they tell you to do.

Your first instinct would probably be to build some sort of if-else logic. e.g. If you knew that the actions possible were lift or bank you could very well just do what's written below.

Example Code:

Output Window

That solution only works as long as you know exactly what methods are going to be called. What if you didn't? What if you did not know all the actions that were possible on the glider object? If only there was a generic way to write the above.

Ruby gives a convenient way for you to call any method on an object by using the send method. send takes, as its first argument, the name of the method that you want to call. This name can either be a symbol or a string.

Hint

Try "sending" the action to the nomad's glider.

Output Window

Additionally, now some of these actions require further arguments. e.g. The command to 'bank' takes a string of either 'left' or 'right', while the command to 'roll' takes the number of degrees it should dive for. Again, send gives us a convenient way to pass arguments to these methods. All further arguments to send after the first (which you'll recall has the name of the method you want called itself) become arguments that get passed down to that method.

Hint

Check if the argument is `nil`. If not, pass it along to the glider.

Output Window

Being sneaky: Calling private methods

Ruby also allows you to call private methods this way. But, chances are you probably don't want to do this. After all, that method was probably declared private for a reason. Let's see if you can extract the secret of the meaning of life from the very secretive monk.

Hint

Perhaps using send will let you get secrets you won't get to otherwise.

Output Window

In fact, we can even send messages to an object which doesn't have the method we are calling defined as we'll see in the chapter "method_missing".

Relay Messages

In this exercise we've defined a method relay. It accepts two parameters - an array of values, and a data_type. The relay method should return a new array, but with all elements converted to data_type.

That means if I pass in an array of numbers, and specify the data_type as s (which stands for 'string'), the method should return another array with all elements converted to strings. This can be done by calling to_s on every element in the array.

Hint

You have two friends: `send` and `Array#map`. Use them wisely!

Output Window

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2014 by Sidu Ponnappa and Srushti