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
120
121
122
123
124
125
126
127
128
129
130
|
require 'rubygems'
require 'facet/hash/stringify_keys'
require 'facet/symbol/to_proc'
require 'pp'
class Hash
def recursively(&block)
yield inject({}) { |hash, (key, value)|
if value.is_a?(Hash)
hash[key] = value.recursively(&block)
else
hash[key] = value
end
hash
}
end
def recursively!(&block)
replace(recursively(&block))
end
def old_recursively(&block)
inject({}) do |hash, (key, value)|
if value.is_a?(Hash)
hash[key] = value.old_recursively(&block)
else
hash[key] = value
end
yield hash
end
end
end
class Array
def recursively(&block)
map do |item|
if item.is_a?(self.class)
item.recursively(&block)
else
yield item
end
end
end
def recursively!(&block)
replace(recursively(&block))
end
def new_recursively(&block)
yield map { |item|
if item.is_a?(self.class)
item.new_recursively(&block)
else
item
end
}
end
end
nested = [ 'a', 'b', [ 'c', 'd', [ 'e', 'f' ] ], 'g', [ 'h' ] ]
puts "=== New Array#recursively"
nested.new_recursively do |x|
pp x
end
puts "=== End"
puts "=== New nested.recursively(&:upcase)"
begin
pp nested.new_recursively(&:upcase)
rescue => e
puts e
end
puts "=== End"
puts "=== Old Array#recursively"
nested.recursively do |x|
pp x
end
puts "=== End"
puts "=== Old nested.recursively(&:upcase)"
pp nested.recursively(&:upcase)
puts "=== End"
hash = {
:a => 1,
:b => 2,
:c => {
:ca => 1,
:cb => 2,
:cc => 3,
:cd => {
:cda => 1,
:cdb => 2
},
:ce => 5
},
:d => {
:da => 1,
:db => 2
}
}
puts "=== New Hash#recursively"
hash.recursively do |x|
pp x
end
puts "=== End"
puts "=== New hash.recursively(&:stringify_keys)"
pp hash.recursively(&:stringify_keys)
puts "=== End"
puts "=== Old Hash#recursively"
hash.old_recursively do |x|
pp x
x end
puts "=== End"
puts "=== Old hash.recursively(&:stringify_keys)"
pp hash.old_recursively(&:stringify_keys)
puts "=== End"
|