-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rb
119 lines (105 loc) · 2.53 KB
/
main.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
119
module Enumerable
UNDEFINED = Object.new
def my_each
return to_enum(:my_each) unless block_given?
arr = to_a
i = 0
while i < arr.length
yield(arr[i])
i += 1
end
arr
end
def my_each_with_index
return to_enum(:my_each_with_index) unless block_given?
arr = to_a
i = 0
while i < arr.length
yield(arr[i], i)
i += 1
end
arr
end
def my_select
return to_enum(:my_select) unless block_given?
result = []
my_each { |i| result << i if yield(i) }
result
end
def my_all?(arg = UNDEFINED)
unless block_given?
if arg != UNDEFINED
my_each { |x| return false unless arg === x }
else
my_each { |x| return false unless x }
end
return true
end
my_each { |i| return false unless yield(i) }
true
end
def my_any?(arg = UNDEFINED, &block)
unless block_given?
if arg != UNDEFINED
my_each { |x| return true if arg === x }
else
my_each { |x| return true if x }
end
return false
end
my_each { |i| return true if block.call(i) }
false
end
def my_none?(arg = UNDEFINED, &block)
!my_any?(arg, &block)
end
def my_count(arg = UNDEFINED)
arr = if arg.is_a? String
split('')
else
arg
end
count = 0
unless block_given?
if arg != UNDEFINED
arr.my_each { |x| count += 1 if x == arg }
return count
end
return length
end
my_each { |i| count += 1 if yield(i) }
count
end
def my_map(my_proc = UNDEFINED)
return to_enum(:my_map) unless block_given?
result = []
arr = to_a
if my_proc == UNDEFINED
arr.my_each_with_index { |_, y| result << yield(arr[y]) }
else
arr.my_each_with_index { |_, y| result << my_proc.call(arr[y]) }
end
result
end
def my_inject(*arg)
new_arr = to_a
accumulator = arg[0]
if arg[0].class == Symbol
accumulator = new_arr[0]
new_arr = new_arr[1..-1]
new_arr.my_each { |x| accumulator = accumulator.send(arg[0], x) }
elsif arg[0].class < Numeric && arg[1].class != Symbol
new_arr.my_each { |x| accumulator = yield(accumulator, x) }
elsif arg[0].class < Numeric && arg[1].class == Symbol
new_arr.my_each { |x| accumulator = accumulator.send(arg[1], x) }
else
accumulator = new_arr[0]
new_arr = new_arr[1..-1]
new_arr.my_each { |x| accumulator = yield(accumulator, x) }
end
accumulator
end
end
def multiply_els(arg)
arg.my_inject(:*)
end