-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenumerables.rb
118 lines (104 loc) · 2.7 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
module Enumerable
def my_each
return to_enum(:my_each) unless block_given?
i = 0
while i < to_a.length
yield(to_a[i])
i += 1
end
self
end
def my_each_with_index
return to_enum(:my_each_with_index) unless block_given?
i = 0
arr = to_a
while i < arr.length
yield(arr[i], i)
i += 1
end
arr
end
def my_select
return to_enum(:my_select) unless block_given?
i = []
my_each do |value|
i.push(value) if yield(value)
end
i
end
def my_all?(arg = nil)
if block_given?
my_each { |value| return false if yield(value) != true }
elsif arg.nil?
my_each { |value| return false if value.nil? || value == false }
elsif !arg.nil? && (arg.is_a? Class)
my_each { |value| return false unless [value.class, value.class.superclass].include?(arg) }
elsif !arg.nil? && arg.instance_of?(Regexp)
my_each { |value| return false unless arg.match(value) }
else
my_each { |value| return false if value != arg }
end
true
end
def my_any?(arg = nil)
if block_given?
my_each { |value| return true if yield(value) }
elsif arg.nil?
my_each { |value| return true if value }
elsif !arg.nil? && (arg.is_a? Class)
my_each { |value| return true if [value.class, value.class.superclass].include?(arg) }
elsif !arg.nil? && arg.instance_of?(Regexp)
my_each { |value| return true if arg.match(value) }
else
my_each { |value| return true if value == arg }
end
false
end
def my_none?(arg = nil)
arr = to_a
if block_given?
arr.length.times { |i| return false if yield(arr[i]) }
elsif !arg.nil?
return false unless arr.grep(arg).empty?
else
arr.length.times { |i| return false unless arr[i].nil? || arr[i] == false }
end
true
end
def my_count(arg = nil)
counter = 0
if block_given?
my_each { |x| counter += 1 if yield(x) }
elsif !block_given? && arg.nil?
counter = length
else
counter = my_select { |x| x == arg }.length
end
counter
end
def my_map(proc = nil)
return to_enum(:my_map) unless block_given? || !proc.nil?
arr = []
if !proc.nil?
my_each { |value| arr << proc.call(value) }
else
my_each { |value| arr << yield(value) }
end
arr
end
def my_inject(total = nil, n = nil)
if total.is_a?(Symbol)
n = total
total = nil
end
if !block_given? && !n.nil?
my_each { |value| total = total.nil? ? value : total.send(n, value) }
else
my_each { |value| total = total.nil? ? value : yield(total, value) }
end
total
end
end
def multiply_els(arr)
arr.my_inject { |total, n| total * n }
end