Fill array with element N times

Solution 1:

For immutable objects like Fixnums etc

Array.new(5, 1234) # Assigns the given instance to each item
# => [1234, 1234, 1234, 1234, 1234]

For Mutable objects like String Arrays

Array.new(5) { "Lorem" } # Calls block for each item
# => ["Lorem", "Lorem", "Lorem", "Lorem", "Lorem"]

Solution 2:

This should work:

[1234] * 5
# => [1234, 1234, 1234, 1234, 1234]

Solution 3:

Although the accepted answer is fine in the case of strings and other immutable objects, I think it's worth expanding on Max's comment about mutable objects.

The following will fill an array of elements with 3 individually instantiated hashes:

different_hashes = Array.new(3) { {} } # => [{}, {}, {}]

The following will fill an array of elements with a reference to the same hash 3 times:

same_hash = Array.new(3, {}) # => [{}, {}, {}]

If you modify the first element of different_hashes:

different_hashes.first[:hello] = "world"

Only the first element will be modified.

different_hashes # => [{ hello: "world" }, {}, {}]

On the other hand, if you modify the first element of same_hash, all three elements will be modified:

same_hash.first[:hello] = "world"
same_hash # => [{ hello: "world" }, { hello: "world" }, { hello: "world" }]

which is probably not the intended result.

Solution 4:

You can fill the array like this:

a = []
=> []

a.fill("_", 0..5) # Set given range to given instance
=> ["_", "_", "_", "_", "_"]

a.fill(0..5) { "-" } # Call block 5 times