Fill array with element N times

Ruby

Ruby Problem Overview


I want to fill an array with 1 element but 5 times. What I got so far.

number = 1234
a = []

5.times { a << number }
puts a # => 1234, 1234, 1234, 1234, 1234

It works but this feels not the ruby way. Can someone point me in the right direction to init an array with 5 times the same value?

Ruby Solutions


Solution 1 - Ruby

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 - Ruby

This should work:

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

Solution 3 - Ruby

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 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAMEView Question on Stackoverflow
Solution 1 - RubysawaView Answer on Stackoverflow
Solution 2 - RubyMarek LipkaView Answer on Stackoverflow
Solution 3 - RubyhjingView Answer on Stackoverflow
Solution 4 - RubyAlexander LunaView Answer on Stackoverflow