-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenumerables.rb
84 lines (70 loc) · 1.14 KB
/
enumerables.rb
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
module Enumerable
def my_each
i = 0
while i < size
yield(self[i])
i += 1
end
end
def my_each_with_index
i = 0
while i < size
yield(self[i], i)
i += 1
end
self
end
def my_select
invited_list = []
my_each do |x|
invited_list.push(x) if yield(x)
end
invited_list
end
def my_all?
my_each do |x|
return false unless yield(x)
end
true
end
def my_any?
my_each do |el|
return true if yield(el)
end
false
end
def my_none?
my_each do |el|
return false if yield(el)
end
true
end
def my_count
count = 0
my_each do |i|
count += 1 if yield(i) == true
end
count
end
def my_map
mapped = []
my_each do |i|
mapped << (proc.nil? ? proc.call(i) : yield(i))
end
mapped
end
def my_inject(arg = nil, &block)
memo = arg if arg
my_each do |element|
memo = if memo
block.call(memo, element)
else
element
end
end
memo
end
def multiply_els(arr)
arr.my_inject { |x, y| x * y }
end
end