I have two arrays, for example
a = [3, 2, 1]
b = [1, 2, 3]
I need to multiply them and create a third array c
that will be like this
c = [3 * 1, 2 * 2, 1 * 3]
Which method is the best by speed? I need to do this for huge arrays, and time is important.
The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
An array is a data structure that represents a list of values, called elements. Arrays let you store multiple values in a single variable. In Ruby, arrays can contain any data type, including numbers, strings, and other Ruby objects. This can condense and organize your code, making it more readable and maintainable.
Ruby | Array append() function Array#append() is an Array class method which add elements at the end of the array. Syntax: Array.append() Parameter: – Arrays for adding elements. – elements to add. Return: Array after adding the elements at the end.
a.zip(b).map{|x, y| x * y}
This works because zip combines the two arrays into a single array of two element arrays. i.e.:
a = [3, 2, 1]
b = [1, 2, 3]
a.zip(b)
#=> [[3, 1], [2, 2], [1, 3]]
Then you use map to multiply the elements together. This is done by iterating through each two element array and multiplying one element by the other, with map returning the resulting array.
a.zip(b).map{|x, y| x * y}
#=> [3, 4, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With