DEV Community

Burdette Lamar
Burdette Lamar

Posted on • Edited on

4 1 1

Ruby Method of the Day: Array.new with Block

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.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay