Array.new(size) { |index| }

Hi guys !

Is there a method like this :

Array.new(n) { |i| ...}

but that works with an existing array ? Like that :

array.append(5) { |i| ... }

?

Thank U ! :slight_smile:

S茅bastien

路路路

--
Posted via http://www.ruby-forum.com/.

array.each_index { |i| ...} ?

Saludos,
Ulises

路路路

2014-03-13 13:21 GMT-05:00 S茅bastien Durand <lists@ruby-forum.com>:

Hi guys !

Is there a method like this :

Array.new(n) { |i| ...}

but that works with an existing array ? Like that :

array.append(5) { |i| ... }

?

Thank U ! :slight_smile:

S茅bastien

--
Posted via http://www.ruby-forum.com/\.

--

Saludos,
Ulises

Dear S茅bastien,

Try the 2 options bellow and see if any fits what you need.

ary = Array.new (5) { |i| i }

=> [0, 1, 2, 3, 4]

# You can Array#fill at the end

ary.fill(5..9) { |i| i*10 }

=> [0, 1, 2, 3, 4, 50, 60, 70, 80, 90]

# You can overwrite previous values

ary.fill(0..4) { |i| i*2 }

=> [0, 2, 4, 6, 8, 50, 60, 70, 80, 90]

# You can Array#concat at the end of the Array.

ary.concat Array.new (5) { |i| i*100 }

=> [0, 2, 4, 6, 8, 50, 60, 70, 80, 90, 0, 100, 200, 300, 400]

Hope it helps you,
Abinoam Jr.

路路路

On Thu, Mar 13, 2014 at 3:42 PM, ulises <ulises.cabanillas@gmail.com> wrote:

array.each_index { |i| ...} ?

Saludos,
Ulises

2014-03-13 13:21 GMT-05:00 S茅bastien Durand <lists@ruby-forum.com>:

Hi guys !

Is there a method like this :

Array.new(n) { |i| ...}

but that works with an existing array ? Like that :

array.append(5) { |i| ... }

?

Thank U ! :slight_smile:

S茅bastien

--
Posted via http://www.ruby-forum.com/\.

--

Saludos,
Ulises

Abinoam Jr. wrote in post #1139754:

Dear Sbastien,

# You can Array#fill at the end

ary.fill(5..9) { |i| i*10 }

=> [0, 1, 2, 3, 4, 50, 60, 70, 80, 90]

# You can overwrite previous values

ary.fill(0..4) { |i| i*2 }

=> [0, 2, 4, 6, 8, 50, 60, 70, 80, 90]

This is cool, any where inside the array, you can play.. :slight_smile: Nice +1.

路路路

--
Posted via http://www.ruby-forum.com/\.