W
Wil
Hi all,
I've been using Ruby for a while now, and have enjoyed it immensely.
However, I haven't yet found how to map more than one array at once.
The common example is calculating the dot product. You'd need to
iterate through each array at the same time to multiply the elements.
However, map only operates on one list at a time. I wanted to avoid
For Loops. Therefore, I end up having to do something like this
instead:
def dot_prod(a,b)
return 0 if a.length != b.length
c = []
a.each_with_index { |e, i| c << e * b }
c.inject { |e, t| t += e }
end
Ugly. or use recursion:
def dot_prod(a, b)
return 0 if a.length != b.length
a.empty? ? 0 : a.first * b.first + dot_prod(a[1..-1], b[1..-1])
end
Better, but a map/inject solution would be desired. Does anyone else
know of a way to iterate through two arrays without the use of an
index? Or do people just roll their own multiple array map function?
I've been using Ruby for a while now, and have enjoyed it immensely.
However, I haven't yet found how to map more than one array at once.
The common example is calculating the dot product. You'd need to
iterate through each array at the same time to multiply the elements.
However, map only operates on one list at a time. I wanted to avoid
For Loops. Therefore, I end up having to do something like this
instead:
def dot_prod(a,b)
return 0 if a.length != b.length
c = []
a.each_with_index { |e, i| c << e * b }
c.inject { |e, t| t += e }
end
Ugly. or use recursion:
def dot_prod(a, b)
return 0 if a.length != b.length
a.empty? ? 0 : a.first * b.first + dot_prod(a[1..-1], b[1..-1])
end
Better, but a map/inject solution would be desired. Does anyone else
know of a way to iterate through two arrays without the use of an
index? Or do people just roll their own multiple array map function?