Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
subtracting arrays
Jason
6/11/2008 11:06:00 PM
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.
--
Posted via
http://www.ruby-...
.
3 Answers
Avdi Grimm
6/11/2008 11:10:00 PM
0
On Wed, Jun 11, 2008 at 7:06 PM, Jason Lillywhite
<jason.lillywhite@gmail.com> 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:...
Developer Blog:
http:...
/devblog/
Twitter:
http://twitte...
Journal:
http://avdi.livej...
Avdi Grimm
6/11/2008 11:11:00 PM
0
On Wed, Jun 11, 2008 at 7:06 PM, Jason Lillywhite
<jason.lillywhite@gmail.com> 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:...
Developer Blog:
http:...
/devblog/
Twitter:
http://twitte...
Journal:
http://avdi.livej...
Jason
6/11/2008 11:21:00 PM
0
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.
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
subtracting arrays
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password