Sending a Message
So far, we've seen the standard way to send a message to Ruby objects using the dot (.
) notation. Another way to send a message to a Ruby object is through the send
method, as shown in the following code:
array = [1,2,3] array.length # standard way of sending a message to an object array.send(:length) # using the send method array.send("length") # You can send a symbol or a string
send
also supports passing arguments to methods:
array.send(:last, 2)
send
will pass the positional arguments to the method in the same order that the method defines them. In other words, the second argument to send
is really the first argument to the method that is actually being called. The third argument to send
is the second argument to the method being called, and so on.
Let's take a look at some additional cases.
In the following example, we send
the each
method and can still pass a block:
[1,2,3].send(:each) do |i| puts i end
Let&apos...