OneBite.Dev - Coding blog in a bite size

insert an element at a specific index in an array in Ruby

Code snippet on how to insert an element at a specific index in an array in Ruby

  array = [1,2,3,4,5]
  index = 2
  new_item = 100
  array.insert(index, new_item)

This code snippet is using the method insert to add an element to an existing array. First, the code creates an array with the elements 1, 2, 3, 4, 5. Then, it sets the index of the new element to be 2. Finally, it sets the new item to be 100. This means that the new item will be inserted between the elements 2 and 3 at index 2. The insert method takes two arguments, the first being the location in the array at which the element should be added, and the second is the item itself. By using the insert method, the new item can easily be added to the array at a specific index.

ruby