insert an element into an array at a specific index in ruby

To insert an element at a specific index in a Ruby array, you can use the insert method. The method takes two arguments: the index at which to insert the element, and the element to insert.

main.rb
my_array = ["foo", "bar", "baz"]
my_array.insert(1, "qux")
puts my_array.inspect
# Output: ["foo", "qux", "bar", "baz"]
120 chars
5 lines

In this example, we're inserting the string "qux" at index 1 in my_array. The resulting array is ["foo", "qux", "bar", "baz"].

related categories

gistlibby LogSnag