Skip to content

Instantly share code, notes, and snippets.

@DmitryBash
Last active December 18, 2023 14:05
Show Gist options
  • Save DmitryBash/e99cffcf17e2c09cd7c2e51a3028fe36 to your computer and use it in GitHub Desktop.
Save DmitryBash/e99cffcf17e2c09cd7c2e51a3028fe36 to your computer and use it in GitHub Desktop.
reverse array
def reverse_array(arr)
return arr if arr.empty?
arr = arr.dup
start_index = 0
end_index = arr.length - 1
while start_index < end_index
arr[start_index], arr[end_index] = arr[end_index], arr[start_index]
start_index += 1
end_index -= 1
end
arr
end
origin_array = [1, 2, 3, 4]
reverse_array(origin_array) # => [4, 3, 2, 1]
reverse_array([]) # => []
origin_array # => [1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment