Ruby Array - Addition

  • + 0 comments

    Here’s how you can implement the three functions in Ruby:

    def end_arr_add(arr, element) # Add element to the end of the array arr.push(element) arr end

    def begin_arr_add(arr, element) # Add element to the beginning of the array arr.unshift(element) arr end

    def index_arr_add(arr, index, *elements) # Add one or more elements starting at the given index arr.insert(index, *elements) arr end

    Explanation:

    push adds an element to the end of the array.

    unshift adds an element to the beginning.

    insert(index, *elements) adds one or more elements starting at the specified index.

    Examples:

    x = [1,2] end_arr_add(x, 3) # => [1,2,3] begin_arr_add(x, 0) # => [0,1,2,3] index_arr_add(x, 1, 5, 6) # => [0,5,6,1,2,3]

    This covers adding elements at the beginning, end, and any index, including multiple elements.