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