Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby- Adding/subtracting elements from one array with another array

I do this:

a = [1,2,3,4]  
b = [2,3,4,5]  
c = b - a  
put c 

I get this answer -> [1]
I want this answer -> [1,1,1,1] (like matrix addition/subtraction)

I tried this:

c.each {|e| c[e] = b[e] - a[e]}  

but I get this answer: [1,0,0,0]

Can someone give me a correct way to do this? Thanks a lot!

like image 974
subyman Avatar asked Apr 10 '11 03:04

subyman


People also ask

How do you subtract two arrays in Ruby?

You can use the - operator on two arrays to get an array that removes items or elements that appear in the other. This way, we get a new array that does not contain elements present in both arrays.

How do you subtract two arrays from each other?

Subtract Two ArraysCreate two arrays, A and B , and subtract the second, B , from the first, A . The elements of B are subtracted from the corresponding elements of A . Use the syntax -C to negate the elements of C .

How do you add an element from one array to another 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 do you subtract an array from an array?

Description. C = A – B subtracts array B from array A by subtracting corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.


2 Answers

You could use zip:

a.zip(b).map { |x, y| y - x }
# => [1, 1, 1, 1]

There is also a Matrix class:

require "matrix"

a = Matrix[[1, 2, 3, 4]]
b = Matrix[[2, 3, 4, 5]]
c = b - a
# => Matrix[[1, 1, 1, 1]]
like image 163
Todd Yandell Avatar answered Sep 18 '22 11:09

Todd Yandell


You can use each_with_index and map.

 c = b.each_with_index.map { |n,i| n - a[i] }
 # => [1, 1, 1, 1]
like image 44
Andy Avatar answered Sep 19 '22 11:09

Andy