Add value in empty array at specific index

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.

Is there any method for this ?

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
1 Like

Okay thank you. If I use static array, is it possible to extend the size later ?

Well, StaticArray is static, but ordinary arrays can be expanded at will.

arr = [""] * 10
arr[4] = "bob"
arr = arr + ([""] * 10)
arr[12] = "joe"
p arr

There is no method for this. You’ll have to write your own, something like

class Array(T)
  def []= (index : Int32, val : T, *, filler : T)
    if index >= size
      concat([filler] * (index - size + 1))
    end
    self[index] = val
  end
end

a = [] of String
a[10, filler: ""] = "ten"
#=> ["", "", "", "", "", "", "", "", "", "", "ten"]