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[i] - b[i]
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.
On Wed, Jun 11, 2008 at 7:06 PM, Jason L.
[email protected] wrote:
while i < 3 do
c << a[i] - b[i]
i += 1
end
BTW, this kind of loop is what Enumerable#each_with_index is for.
–
Avdi
Home: http://avdi.org
Developer Blog: Avdi Grimm, Code Cleric
Twitter: http://twitter.com/avdi
Journal: http://avdi.livejournal.com
OK, I see.
so this works:
a = [1,2,3]
b = [1,1,1]
c = []
i = 0
while i < 3 do
c << a[i] - b[i]
i += 1
end
p c.each_with_index {|item,index|}
Thanks.
On Wed, Jun 11, 2008 at 7:06 PM, Jason L.
[email protected] wrote:
I suspect there is a cleaner way to do this with inject or collect.
a.zip(b).map do |x, y| x - y end
=> [0, 1, 2]
–
Avdi
Home: http://avdi.org
Developer Blog: Avdi Grimm, Code Cleric
Twitter: http://twitter.com/avdi
Journal: http://avdi.livejournal.com