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
38
39
| # Array operations
arr = [1, 2, 3, 4, 5]
arr.length # => 5
arr.first # => 1
arr.last # => 5
arr.push(6) # => [1, 2, 3, 4, 5, 6]
arr.pop # => 6
arr.include?(3) # => true
# how to insert an element at the beginning of the array
arr.unshift(0) # => [0, 1, 2, 3, 4, 5]
# how to insert an element at the end of the array
arr.push(6) # => [0, 1, 2, 3, 4, 5, 6]
# how to insert an element at a specific index
arr.insert(0, 0) # => [0, 0, 1, 2, 3, 4, 5]
# how to remove an element at a specific index
arr.delete_at(0) # => [0, 1, 2, 3, 4, 5]
# how to remove an element at a specific **value**
arr.delete(0) # => [1, 2, 3, 4, 5]
# how to remove all elements from the array that satisfy the condition
arr.delete_if { |n| n.even? } # => [1, 3, 5] # Removes all elements that satisfy the condition
# how to remove all elements from the array
arr.clear # => []
# how to remove the first element from the array and return the removed element
arr.shift # => [0] # Removes the first element from the array and returns it
# how to insert an element at the beginning of the array
arr.unshift(-1) # => [0, 0, 1, 2, 3, 4, 5]
arr.unshift("a" , "b") # => ["a", "b", 0, 0, 1, 2, 3, 4, 5]
# how to remove the last element from the array and return the removed element
arr.pop # => [5] # Removes the last element from the array and returns it
|