Since you want to multiply two arrays, we have to assume they are of same size.
Hence, below is a simple way to multiply them - it has O(n) time complexity. Other answers are also equally good, you can pick any one
a = [3, 2, 1]
b = [1, 2, 3]
a.size.times.collect { |i| a[i] * b[i] }
#=> [3, 4, 3]
If time is really of the essence, then, you may want to use multiple threads. A sample program demonstrating the concept is shown below. You can build upon it based on your specific needs.
a = [3, 2, 1]
b = [1, 2, 3]
num_cores = 2 # This decides number of threads, ideally equal to number of cores
ary_size = a.size
# We need to collect result of each thread as separate sub-array.
# We will use result array-of-array so that order of result is preserved
results = Array.new(num_cores, [])
# Divide the array indexes into equal parts
index_splits = (0...ary_size).each_slice(num_cores)
threads = []
# Process each sub-array in a thread of its own
index_splits.each_with_index do |ary, i|
threads << Thread.new do
results[i] = ary.collect {|j| a[j] * b[j] }
end
end
threads.each {|t| t.join}
p results.flatten
#=> [3,4,3]