I just read about what send does in Ruby and I’m still confused when looking at this code (it’s from a quiz but its past due date anyways)
x = [1,2,3]
x.send :[]=,0,2
x[0] + x.[](1) + x.send(:[],2)
I understand that the first line assigns an array to x
then I don’t understand what :[] = ,0,2 does at all and i dont understand why send is needed there
I dont get what x.[](1) does and x.send(:[],2) do on the last line
I’m really confused and I just cant find this information online.
I found the what send does but I’m still a little bit confused and a lot of bit confused about this code as a whole.
First of all, things like
[](array index) and[]=are just methods in Ruby.xis anArray, and arrays have a[]=method, which accepts two arguments, an index and a value to set.Using
sendlets you pass an arbitrary “message” (method call) to object, with arbitrary parameters.You could call
x.send :sort, for example, to send the “sort” message to the array. Sort doesn’t need any parameters, though, so we don’t have to pass anything extra to it.x#[]=, on the other hand, accepts two arguments. Its method can be thought of to look like this:So, we can just invoke it with
send :[]=, 0, 2, which is just like callingx[0] = 2. Neat, huh?