Markus Schulz Markus Schulz - 6 months ago 18
Ruby Question

How to recursively invoke methods like: q[0].from(q[1].from(q[2].from(q[3]))) when q size is unknown?

How to recursively invoke methods like:

q[0].from(q[1].from(q[2].from(q[3])))

in Ruby when q size is unknown?

Answer

You can use inject for this:

q.reverse_each.inject do |acc, value|
  value.from(acc)
end

The reverse is needed to get things in the right order. The first time the block is invoked acc is the last element from q, q[3] in your example and value is q[2]. On the next iteration, value is q[1] and acc is the result from the previous block (q[2].from(q[3])) so it calculates

q[1].from(q[2].from(q[3]))

And so on

Comments