I am trying to write a method that takes an array of strings as its argument and returns array.reverse without actually using reverse (using Ruby). Most of my attempts have resulted in adding nils to the array. I can't track this algorithm down. Do you have a solution?
3 Answers
A pretty straightforward way is as follows:
def reverser(array)
reversed = Array.new
array.length.times { reversed << array.pop }
reversed
end
We just pop off the last element of your array and push it into a new array until we've done so with all elements of your array.
3 Comments
Cary Swoveland
It should be noted that this mutates
array
. (Downvote not mine.)sawa
In addition to that, it is essentially the same as Cary's answer (except that this answer is inferior than Cary's).
Garett Arrowood
I clicked this one because I am very new to coding. This seems the most straight ahead. I'm sure Cary's answer is better, but I am not yet familiar many of the methods and syntax.