Say I have many arrays of same size, with some elements, for example one of those could be:
arr = ['a', 'b', 'c', 'd']
I want to call a different function on each element, depending on its index, so I could do this:
arr.each_with_index do do |el, idx|
case idx
when 0
functionA el
when 1
functionB el
# and so on..
end
end
Is there any shorter way to do this? Something similar to assigning to variables:
a, b, c, d = arr
but I want to call functions, instead of doing assignment.
You could prepare an array of funcs and then zip the two together. Something like this:
But my methods are methods, not lambdas…
Here’s a trick how to turn methods to proc objects, so that you can put them in array and call later. Be wary, though, that those calls are more expensive as compared to regular methods (shouldn’t matter, unless you’re already squeezing cycles out of your CPU)