Skip to content

Instantly share code, notes, and snippets.

@Yorgg

Yorgg/reverse-ruby.rb

Last active Aug 29, 2015
Embed
What would you like to do?
Reverse Ruby Methods
#Simple programming challenge in Ruby
#1) Reverse a string and array without using the ruby method 'reverse'
#2) Reverse a string and array recursively
#reverse string
def reverse(s)
i = 0
out = ""
out << s[i -= 1] until i == -s.length
out
end
def recurse_reverse(s)
return s[0] if s.length == 1
s[-1] << recurse_reverse(s[0..-2])
end
#reverse array
def reverse(a)
i = 0
out = []
out << a[i -= 1] until i == -a.length
out
end
def recurse_reverse(a)
return [a[0]] if a.length == 1
a[-1]].concat recurse_reverse(a[0..-2])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment