Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send method in Ruby

Tags:

ruby

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.

like image 367
Xitcod13 Avatar asked Oct 15 '12 08:10

Xitcod13


People also ask

What does the send method do?

The send method takes the first argument that we passed and executes that method on the object. If the object responds to that method, then the output will be successful. Otherwise, it will produce an error.

What is metaprogramming in Ruby?

Metaprogramming is a technique by which you can write code that writes code by itself dynamically at runtime. This means you can define methods and classes during runtime.

What is * args in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).

What is Respond_to in Ruby?

respond_to? is a Ruby method for detecting whether the class has a particular method on it. For example, @user.respond_to?('eat_food')


2 Answers

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)
end

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

like image 54
Chris Heald Avatar answered Oct 13 '22 19:10

Chris Heald


In Ruby, a[0] = 2 is actually syntactic sugar for a.[]=(0, 2).

Knowing this, that's what your second line does—it calls the []= method with two arguments using metaprogramming, as you correctly guessed.

This is the same for your third line: a[0] is syntactic sugar in Ruby for x.[](0).

The following code is a simpler equivalent to your example:

x = [1, 2, 3]
x[0] = 2
x[0] + x[1] + x[2]
like image 24
Eureka Avatar answered Oct 13 '22 18:10

Eureka