Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this code with send :[] work?

Tags:

methods

ruby

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?

like image 567
WCGPR0 Avatar asked Jun 10 '26 17:06

WCGPR0


2 Answers

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.

like image 164
Yu Hao Avatar answered Jun 12 '26 09:06

Yu Hao


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

like image 41
PSkocik Avatar answered Jun 12 '26 10:06

PSkocik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!