Last Updated: February 25, 2016
·
229
· pitchinvasion

JavaScript-style callbacks in Ruby

One nice feature of JavaScript is the fact that we can pass functions as arguments, such as in the example below:

function square(integer) {
  return integer * integer;
}

[1,2,3].map(square);

This is particularly useful when programming in a functional way, as it allows for an extremely clean way of passing callbacks to methods like map.

Being a fan of Ruby, I wondered whether there was a way we could do something similar in Ruby. Turns out there is:

def square(integer)
  integer * integer
end

[1,2,3].map(&method(:square)) # => [1,4,9]

The code here is basically doing the same thing as in the JavaScript above, but with a little more syntax required.

What is going in here is we are taking advantage of the fact that when we call method(:square) it returns the square method as a Method object. We then use & to pass this as a block to the map method.

Definitely not as simple as the JavaScript, but great for doing functional programming in Ruby.