Skip to content

Commit a045471

Browse files
committed
Operations with ruby array and create MyArray class.
1 parent edd4a83 commit a045471

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
*.swp

Data-Structurs-Arrays/array.rb

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
strings = ['a','b','c','d']
2+
# 4*4 = 16 bytes of storage is used
3+
4+
puts(strings[2])
5+
6+
#push
7+
strings.append('e') # O(1)
8+
#pop
9+
strings.pop()
10+
strings.pop() # O(1)
11+
12+
#addfirstelement
13+
strings.insert(0,'x') #O(n)
14+
15+
#splice
16+
strings.insert(2,'alien') #O(n)
17+
18+
print(strings)
19+
puts(strings.length)

Data-Structurs-Arrays/my_array.rb

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class MyArray
2+
def initialize
3+
@length = 0
4+
@data = {}
5+
end
6+
7+
def length
8+
@length
9+
end
10+
11+
def to_s
12+
puts @data
13+
end
14+
15+
def push(item)
16+
@data[@length] = item
17+
@length += 1
18+
end
19+
20+
def pop
21+
last_item = @data[@length-1]
22+
@data.delete(@length-1)
23+
@length -= 1
24+
last_item
25+
end
26+
27+
def delete(index)
28+
del_item = @data[index]
29+
(index...@length).each do |i|
30+
@data[i] = @data[i+1]
31+
end
32+
@data.delete(@length-1)
33+
@length -= 1
34+
del_item
35+
end
36+
end
37+
38+
array = MyArray.new
39+
array.push(3)
40+
array.pop
41+
array.push('hi')
42+
array.push(34)
43+
array.push(20)
44+
array.push('hey')
45+
array.push('welcome')
46+
array.delete(3)
47+
array.pop
48+
array.pop
49+
puts(array)

0 commit comments

Comments
 (0)