Skip to content

Instantly share code, notes, and snippets.

@alexfish
Created April 18, 2011 23:35
Show Gist options
  • Save alexfish/926521 to your computer and use it in GitHub Desktop.
Save alexfish/926521 to your computer and use it in GitHub Desktop.
Reverse an array in Ruby without .reverse
i = 0
j = array.length - 1
while i < j do
last = array[j]
first = array[i]
array[i] = last
array[j] = first
i += 1
j -= 1
end
puts array
@PsixokoT
Copy link

array = [1, 2, 3, 4, 5]
(array.count / 2).times do |i|
array[i], array[-(i + 1)] = array[-(i + 1)], array[i]
end
puts array

@parkh
Copy link

parkh commented Aug 7, 2017

array = [1, 2, 3]
array_reversed = []
array.each do |x|
array_reversed.unshift x
end

@kapil-chouhan-roostify
Copy link

def reverse(array)
rev = []
rev << array.pop until array.empty?
rev
end

@danielchaves2
Copy link

danielchaves2 commented Sep 20, 2022

def reverse(a)
a.length.times do |i|
a.insert(i, a.pop)
end
end

@neeraj5511
Copy link

def reverse_array(arr)
length = arr.length
half_length = length / 2

(0...half_length).each do |i|
# Swap elements from the beginning and end of the array
arr[i], arr[length - 1 - i] = arr[length - 1 - i], arr[i]
end

return arr
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment