Hi guys, I have a special request. I would like basically to add a value in an empty array at a specific index, and if this index is out of bound (because it is empty), instead of having an error, fill up the array with empty values.
BUT if I the array is not empty, don’t overwrite the existing values, just fill the gap with empty values. Let me know if it is not clear.
This is an example of what I would like:
array is an empty array of string
We add "hello" to the index 2
=> ["","","hello"]
Now we change the value of index 1 with "bye"
=> ["","bye","hello"]
Now we had again another value at index 5, with value "good"
=> ["","bye","hello","","","good"]
Basically this example show the behavior I would like.
The array needs at least as many elements available as the index you’re trying to set, so one option is to “preallocate” the number of elements using an array (or a StaticArray).
arr = StaticArray(String, 10).new(“”)
arr[4] = “bob”
p arr
Another alternative if you want only specific indices is to use a hash with integers as keys:
hsh = Hash(UInt32, String).new
hsh[4] = “bob”
p hsh