Xitcod13 Xitcod13 -4 years ago 122
Ruby Question

send method in Ruby

I just read about what

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
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.

Answer Source

First of all, things like [] (array index) and []= are just methods in Ruby. x is an Array, and arrays have a []= method, which accepts two arguments, an index and a value to set.

Using send lets 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:

def []=(index, value)
  self.set_value_at_index(index, value)

So, we can just invoke it with send :[]=, 0, 2, which is just like calling x[0] = 2. Neat, huh?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download