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!
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.
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 .
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).
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.
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]]
You can use each_with_index
and map
.
c = b.each_with_index.map { |n,i| n - a[i] }
# => [1, 1, 1, 1]
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