Ruby Method of the Day: Array.new with Block

Burdette Lamar - Jun 27 '23 - - Dev Community

One of the call sequences for method Array.new takes a block, allowing you to populate the new array with anything you want:

Array.new(size) {|index| ... }
Enter fullscreen mode Exit fullscreen mode

This returns an array of the given size; the block is called with each successive integer index; the block's return value becomes the element for that index:

a = Array.new(3) {|index| "Element #{index}" }
a # => ["Element 0", "Element 1", "Element 2"]
Enter fullscreen mode Exit fullscreen mode

More methods at #rubymethodoftheday.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player