Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I multiply two arrays in Ruby?

Tags:

arrays

ruby

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.

like image 233
Maxim 666 Avatar asked Dec 22 '15 11:12

Maxim 666


People also ask

How do you multiply in Ruby?

The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).

How do I merge two arrays in Ruby?

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).

How does array work in Ruby?

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.

What is append in Ruby?

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.


1 Answers

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]
like image 63
sawa Avatar answered Sep 22 '22 07:09

sawa