The following code generates an output of 9. I understand send is simply calling the method :[], but am confused how the parameters work.
x = [1,2,3]
x.send :[]=,0,4 #why is x now [4,2,3]
x[0] + x.[](1) + x.send(:[],2) # 4 + 2 + 3
How do line 2 and line 3 work?
Object#send provides another way to invoke a method.
x.send :[]=,0,4
is saying, invoke []= method on x, and pass the argument 0, 4, it's equivalent to:
x[0] = 4
The name send is because in Ruby, methods are invoked by sending a message to an object. The message contains the method's name, along with parameters the method may need. This idea comes from SmallTalk.
x.send(:[]=, 0, 4)
is the same* as
x.[]=(0, 4)
which has the syntactic sugar of
x[0] = 4
which should be familiar from other languages. Parentheses are, of course, optional.
The .send or .public_send variety has the advantage that the method to invoke doesn't have to be hardcoded—it can come from a variable.
All this is congruent with ruby's paradigm of object orientedness: objects communicate with each other by sending messages, and the messages trigger code execution.
*almost, #send will invoke private methods too
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With