West Coast Charlie West Coast Charlie - 1 month ago 15
Ruby Question

ruby** reverse array without using reverse method

This is my array and custom method to reverse an array output without using the reverse method. not sure where it broke, tried running it in console, no dice.

numbers = [1, 2, 3, 4, 5, 6]

def reversal(array)
do |item1, item2| item2 <=> item1
end

p reversal(numbers)

Answer

Here's one way to handle this. This is not very efficient but works.

def reversal(array)
    reversed = []
    loop do
        reversed << array.pop
        break if array.empty?
    end
    reversed
end

Here is another implementation that does the same thing:

def reversal(array)
    array.each_with_index.map do |value, index|
        array[array.count-index-1]
    end
end
Comments