insert element in the middle of an array ruby

To insert an element in the middle of an array in Ruby, you can follow these steps:

  1. Determine the middle index of the array by dividing the length of the array by 2 and rounding down to the nearest whole number. You can use the .length method to get the length of the array.

  2. Use the .insert method to insert the element at the middle index. This method takes two arguments: the index at which to insert the element and the element itself.

Here's an example of how you can do it:

array = [1, 2, 3, 4, 5]
element = 10

middle_index = array.length / 2

array.insert(middle_index, element)

After executing this code, the array will be [1, 2, 10, 3, 4, 5], with the element 10 inserted in the middle at index 2.