if you very often need this, extend the Array class
class Array
def plus(other)
return (0...self.length()).map {|i| self[i] + other[i]}
end
end
a = Array.new(3, 1)
b = Array.new(3, 2)
c = a.plus(b)
p c
Regards
Clemens
> -----Original Message-----
> From: Martin Kahlert [mailto:martin.kahlert / infineon.com]
> Sent: Montag, 19. November 2001 10:42
> To: ruby-talk / ruby-lang.org
> Subject: [ruby-talk:25834] HowTo deal with arrays?
>
>
> Hi!
> I want to do something like that:
>
> a = Array.new(1000000, 1)
> b = Array.new(1000000, 2)
> c = Array.new(1000000)
>
> for i in 0 ... a.length
> c[i] = a[i] + b[i]
> end
>
> This looks a bit too C-ish for me.
>
> Should i use
> (0 ... a.length).each {|i| c[i] = a[i] + b[i]}
> or
> a.length.times {|i| c[i] = a[i] + b[i]}
> or
> a.each_index {|i| c[i] = a[i] + b[i]}
>
> Which is the 'ruby way' of doing that?
>
> Background: I did some timing and found
> a.collect! {|x| x+1}
> to be twice as fast as
> for i in 0 ... a.length
> a[i] += 1
> end
>
> --
> The early bird catches the worm. If you want something else for
> breakfast, get up later.
>