How to Initialize an Array on Ruby
Do you know how to initialize an Array of a specific len with the same value in each element, something like [0, 0, 0, 0, 0], to be honest I didn't know.
I ended up with a code like this
arr = []
5.times.each{|i| arr << 0}
It does the work, but I just don't like it, too much code for a simple task. There should be a better way... and there is
What I didn't know is that the Array constructor take two parameters, the first one is the size, and the second one is the default object for the elements. So I can rewrite my code to
```ruby
arr = Array.new(5, 0) # [0, 0, 0, 0, 0]
# You can pass any object, an string by example
arr = Array.new(5, 'N/A') # ["N/A", "N/A", "N/A", "N/A", "N/A"]
```
Array constructors also receive a block, but that is another history
Written by Omar
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#