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?
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.
Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.
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"]
This should work:
[1234] * 5
# => [1234, 1234, 1234, 1234, 1234]
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With