Array.new(n) { |i| }

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

array.each_index { |i| …} ?

Saludos,
Ulises

2014-03-13 13:21 GMT-05:00 Sbastien D. [email protected]:

?

Thank U ! :slight_smile:

Sbastien


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.

Dear Sbastien,

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.