Develop­ment

Ruby's Curry Method and How to Use It

Ruby's Curry Method and How to Use It

Recently, our team needed to pluck out an _n_th element from a nested array. The traditional, straightforward method would be to do something like this:

  array = [[0, ?X, 0, 0], [0, ?Y, 0, 0], [0, ?Z, 0, 0]]
  # => [[0, ?X, 0, 0], [0, ?Y, 0, 0], [0, ?Z, 0, 0]]
  array.map { |nested_array| nested_array[1] }
  # => ["X", "Y", "Z"]

While this is a good approach, we wanted something a bit more flexible. Specifically, we were looking for a way to pass in an index and return the correct result without having to rewrite the same block of code over and over again.

One of the great things about working with a mature dynamic language is the array of tools available to solve problems. Ruby provides us with the curry method.

You might be wondering what exactly the term curry means. In this context, it’s not a delicious Indian dish you can eat with naan and samosas and . . . I’m getting a bit off-track.

Curry is actually a method that allows us to dynamically send arguments to methods while delegating some of the arguments on to the caller at the time of execution. In this case, we have used curry to pass in the index and map to pass in the array to the proc defined in the nth_element method.

Here is the block of code that illustrates that for this particular scenario.:

  def nth_element(index)
    proc = -> (idx, arr) { arr[idx] }
    proc.curry[index]
  end
  array.map &nth_element(1)
  # => ["X", "Y", "Z"]

Pretty great, huh? If you’re interested in learning more, Ruby Docs is a great place to start. They have a helpful explanation of curry available here - ruby docs.

pin-icon phone