I have some cartesian points (i.e. array of two values):
p0 = [0, 0]
p1 = [20, 20]
I need to do some math over it such as (t+2)*p0
or (m/v+2)/p1
. I need to modify each element of the array. How would you do this efficiently? My code is something like this:
pT = [(t + 2) * p0[0], (t + 2) * p0[1]]
but it looks terrible to read. Is there a better way that is more in line with the math form?
How about .map
?
pT = [p0, p1].map { |p| (t + 2) * p }
If you needed to apply a bunch of composed functions for each value, you could do something like:
funcs = [
proc { |p| (t + 2) * p }, # f
proc { |p| (m / v + 2) / p } # g
]
# applies g(f(p)) for each p
pT = [p0, p1].map { |p| funcs.inject(p) { |p, f| p = f[p] } }
Taking this a step further, if you needed a different function for each value:
funcs = [
proc { |p| (t + 2) * p },
proc { |p| (m / v + 2) / p },
proc { |p| p }
]
pT = [p0, p1].zip(funcs).map { |p, f| f[p] }