Reputation: 3643
I am new to ruby , can someone explain what the second and 3rd line do?
a = [6,7,8]
a.send :[]=,0,2
a[0] + a.[](1) + a.send(:[],2)
First line is assigning an array to the variable a.
I am totally lost on second and third line. hope someone can give some detail explannations.
Thanks!!!
Upvotes: 4
Views: 3349
Reputation: 10107
You can try the code in irb and see what happens. send
means sending the following messages to an object. This feature is inherited from Smalltalk.
So a.send :[]=,0,2
means send the parameter :[]=,0,2
to a. The parenthesis is omitted. The first parameter :[]=
is the method to be called by a
. Starting with a :
means it is a symbol. []=
is the method name. The other parameters of send are treated as the parameter of []=
.
As you can see in line 3, a.[](1)
is equivalent to a[1]
in any C-like languages. And a.[]= 0,2
is a[0]=2
.
Upvotes: 2
Reputation: 160833
.send
invokes the method identified by symbol, passing it any arguments specified.
a.send :[]=,0,2
is same as
a.send(:[]=, 0, 2)
Means invoke []= method on the array object with first parameter as 0
and second parameter as 2
.
So this is a[0] = 2
, set the first element of the array to 2
.
After executed a.send :[]=,0,2
, a
becomes [2, 7, 8]
.
a.[](1)
is same as a[1]
a.send(:[], 2)
is same as a.[](2)
which is a[2]
.
So a[0] + a.[](1) + a.send(:[],2)
equals a[0] + a[1] + a[2]
equals 2 +7 + 8
equals 17
.
Upvotes: 14
Reputation: 47472
a.send :[]=,0,2 ###same as a[0] = 2
a.[](1) ### same as a[1]
a.send(:[],2) ## same as a[1]
Upvotes: 3