0

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?

1
  • 2
    Show one of those attempts! Commented Jun 24, 2015 at 3:09

3 Answers 3

2
def reverse a; a.inject([], :unshift) end

reverse(["a", "b", "c"]) # => ["c", "b", "a"]
Sign up to request clarification or add additional context in comments.

Comments

2

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] 

Comments

0

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

It should be noted that this mutates array. (Downvote not mine.)
In addition to that, it is essentially the same as Cary's answer (except that this answer is inferior than Cary's).
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.