One Dimensional Array Append

excerpt: Under the hood look at how to add an element to the end of an array. tags: array-append

Solution Outline

  1. Create a temporary array larger than the original array
  2. Copy the input array values to temp array
  3. Assign the input value to the last position
  4. Change the reference of input array to temp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def append(a, value)
  temp = Array.new(a.size + 1)

  for i in (0..a.size-1)
    temp[i] = a[i]
  end

  temp[a.size] = value
  a = temp

  return a  
end

p append([1,2,3,4,5], 6)