i am Chris Smith

Protocol Engineer, Security Researcher, Software Consultant

Ruby's send method

A pattern I see recurring in my programming is that I need to take an argument, then based on what it is do something, for instance:

def my_method(array_of_args, action)
  if action == :sum
    my_math.sum(array_of_args)
  elsif action == :average
    my_math.average(array_of_args)
  end
end

So in this example, we are taking two arguments, one is an array of numbers, the second is a key that represents the action we want to perform on the array.

I recently discovered a new way of doing this that makes it much simpler. So if we assume that the actions we are passing in are the same name as the methods we have on our object we can do this:

def my_method(array_of_args, action)
  my_math.send action array_of_args
  # my_math.send(action, array_of_args)
end

So .send takes a symbol (or a string) for its first argument which corresponds to the method name. The next n arguments are the arguments that get passed into your method.

One interesting thing I found out about the send method from Stack Overflow is that it will bypass “visibility checks” so it gets around the private designation on methods and could be used to directly test those methods.

This is a little slower than directly calling the method directly (i.e. class.method_name) according to Khelll’s Blog

Further Reading: