subtracting arrays

J

Jason Lillywhite

I suspect there is a cleaner way to do this with inject or collect.

a = [1,2,3]
b = [1,1,1]
c = []
i = 0
while i < 3 do
c << a - b
i += 1
end

p c

=> [0, 1, 2]

I tried a collect but can't figure out how to get variables from outside
the block to work inside the block. I was thinking something like
c = []
c.collect {|a,b| a - b}

but that is not it.
 
J

Jason Lillywhite

OK, I see.

so this works:

a = [1,2,3]
b = [1,1,1]
c = []
i = 0
while i < 3 do
c << a - b
i += 1
end

p c.each_with_index {|item,index|}

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,006
Latest member
LauraSkx64

Latest Threads

Top