Forum: Ruby Array.new(n) { |i| }

56b434ec98414dd9422166b06de1305d?d=identicon&s=25 Sébastien D. (se8)
on 2014-03-13 19:21
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 ! :-)

Sébastien
E2e4d6407aba08242f18c02577b05222?d=identicon&s=25 ulises (Guest)
on 2014-03-13 19:43
(Received via mailing list)
array.each_index { |i| ...} ?

Saludos,
Ulises


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

> ?
>
> Thank U ! :-)
>
> Sbastien
>
> --
> Posted via http://www.ruby-forum.com/.




--

Saludos,
Ulises
09a32175057418748822c587ac08c429?d=identicon&s=25 Abinoam Jr. (abinoampraxedes_m)
on 2014-03-13 20:27
(Received via mailing list)
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.
249c7fd851c5c5ac5a1abdb756472ae1?d=identicon&s=25 Arup Rakshit (my-ruby)
on 2014-03-14 15:45
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.. :-) Nice +1.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.