So I have the task to reverse a multidimensional array recursively. I can't seem to figure out how.
I have written code that, can reverse a multidimensional array but it is not recursive. Could you guys help me make it recursive?
It should look something like this in the end:
ary = [1,[1,22,[5,7,0],8],2,3]
reverse_rek(ary)
#=> [3, 2, [1, 22, [5, 7, 0], 8], 1]
Here is my attempt:
def reverse_rek(ary)
if not ary.is_a?(Array)
raise ArgumentError, "Dies ist kein Array"
end
reverse_rek_intern(ary)
end
def reverse_rek_intern(ary)
len = ary.length-1
reverse_ary =[]
ary.each_index { |index|
reverse_ary[index] = ary[len-index]
}
return reverse_ary
end
Thank you!
index=0, you can reverse the the first and the last indices (you need to actually swap now), and now you need to reverse something smaller, an array starting atindex=1. Consider also when to stop.ary.reverse. Am I missing something? Why should the method be recursive?