Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This question already has an answer here:

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?

share|improve this question

marked as duplicate by Community Jun 24 '15 at 3:46

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2  
Show one of those attempts! – Stan Jun 24 '15 at 3:09
up vote -1 down vote accepted

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.

share|improve this answer
    
It should be noted that this mutates array. (Downvote not mine.) – Cary Swoveland Jun 24 '15 at 7:57
    
In addition to that, it is essentially the same as Cary's answer (except that this answer is inferior than Cary's). – sawa Jun 24 '15 at 19:40
    
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. – Garett Arrowood Jun 24 '15 at 20:12

Many ways to do that. Here's one:

a = (1..10).to_a
  #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

b = a.dup
a.size.times.with_object([]) { |_,c| c << b.pop }
  #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 
share|improve this answer
def reverse a; a.inject([], :unshift) end

reverse(["a", "b", "c"]) # => ["c", "b", "a"]
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.