-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharrayAddition.rb
More file actions
37 lines (30 loc) · 1.04 KB
/
arrayAddition.rb
File metadata and controls
37 lines (30 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Arrays provide a variety of methods that allow to add elements to them.
# push allows one to add an element to the end of the list.
x = [1,2]
x.push(3)
# => [1,2,3]
# insert allows one to add one or more elements starting from a given index (shifting elements after the given index in the process).
x = [1,2]
x.insert(1, 5, 6, 7)
# => [1, 5, 6, 7, 2]
# unshift allows one or more elements to be added at the beginning of the list.
x = [1,2,3]
x.unshift(10, 20, 30)
# => [10, 20, 30, 1, 2, 3]
#solution
def end_arr_add(arr, element)
# Add `element` to the end of the Array variable `arr` and return `arr`
arr.push(element)
end
def begin_arr_add(arr, element)
# Add `element` to the beginning of the Array variable `arr` and return `arr`
arr.unshift(element)
end
def index_arr_add(arr, index, element)
# Add `element` at position `index` to the Array variable `arr` and return `arr`
arr.insert(index,element)
end
def index_arr_multiple_add(arr, index)
# add any two elements to the arr at the index
arr.insert(index,index+1,index+2)
end