Search code examples
arraysmultidimensional-arraycrystal-lang

Infinitely expanding array


How would I go about creating an array of arrays, that can continue that way, adding arrays inside arrays etc, without explicitly knowing how many arrays can contain arrays?

On top of this, out of curiosity, is it possible to change type in place with Arrays, for example if I create an array with ["test"] can I subsequently change it to [["test"]] and so on?

Any comprehensive tutorials on how arrays can be nested etc would be amazing, but currently it's still very difficult to search for crystal topics.


Solution

  • You can use recursive aliases for this (see language reference for alias):

    alias NestedArray = Array(NestedArray) | <YourArrayItemType(s)>
    

    An example (carc.in):

    alias NestedArray = Array(NestedArray) | Int32
    
    array = [] of NestedArray
    array << 1
    array << [2, 3, 4, [5, [6, 7, [8] of NestedArray] of NestedArray] of NestedArray] of NestedArray
    array << Array(NestedArray){Array(NestedArray){10, 11}}
    array # => [1, [2, 3, 4, [5, [6, 7, [8]]]], [[10, 11]]]
    

    Concerning the second question, I am not sure what you mean. You can change the type of a variable like this:

    array = ["test"]
    array = [array]
    array # => [["test"]]