Others, including Chris Morales, have interpreted the task as follows:
p [2,3,3,5,4,4].depthen => [2,[3,3,[[5],4,4]]]
But that doesn't seem right to me, since the element 2 is at a depth
of 1 and not 2. I would think the result should be:
[[2,[3,3,[[5],4,4]]]]
Anyway, here's a solution which handles my interpretation:
class Array
def depthen
result = []
self.each do |depth|
array_end = result
(depth - 1).times do
array_end << [] unless array_end.last.kind_of? Array
array_end = array_end.last
end
array_end << depth
end
result
end
end
And here's what it does:
p [2, 3, 3, 5, 4, 1, 4, 6, 10, 2].depthen
# => [[2, [3, 3, [[5], 4]]], 1, [[[4, [[6, [[[[10]]]]]]]], 2]]
To change it to the other interpretation, just change "depth - 1" to
"depth - 2". And then, presumably, the array depthen is called on
shouldn't have any "1"s in it (although even they're handled
"gracefully" with the depthen method provided).
Eric
====
Are you interested in on-site Ruby training that uses well-designed,
real-world, hands-on exercises?
http://LearnRuby.com