Ruby insert array method
In ruby programming language, insert()method of array are used to insert elements in particular position in array. Syntax of this method as follows.
|Parameter||First is insert position, other is inserting elements|
|Return||Returns reference of resultant array|
This method can take two and more than two parameters. First parameter is indicate the position of inserting elements. And other parameters is indicates inserting object element into the array. When inserting more than one element that is separated by comma.
Ruby insert method example
This method are modifying actual (self) array by inserting new elements. In this section view few example which is describe the its working functionality.
# Example add single element # Our array record = [10,true,[1,2]] # Before insert print(" Before Record : ", record) # Insert element 10 in second index position record.insert(2,10) # After insert print("\n After Record : ", record)
Before Record : [10, true, [1, 2]] After Record : [10, true, 10, [1, 2]]
In above example adding single element which is belong to index position. Note that adding new element at index after that other element index will be changed.
Using of this method are possible to add multiple elements at given index. Lets seen an example.
# Example of add multiple element # Our arrays record = [5, 7, 10, 6] data = [1,4,3] # Before insert print(" Before Record : ", record) # Insert element (8,9,[2,5],data) in third index position record.insert(3,8,9,[2,5],data) # After insert print("\n After Record : ", record)
Before Record : [5, 7, 10, 6] After Record : [5, 7, 10, 8, 9, [2, 5], [1, 4, 3], 6]
In case positioned are greater than array length. Then in this situation, it method are add nil value to previous position which is not exists in array. See this example.
# Our array record = [1,2,3] # Before insert print(" Before Record : ", record) # Insert element ([10,20]) in fifth index position record.insert(5,[10,20]) # After insert print("\n After Record : ", record)
Before Record : [1, 2, 3] After Record : [1, 2, 3, nil, nil, [10, 20]]
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.