Last active
August 29, 2015 14:26
-
-
Save Yorgg/cab20dc309e1f009e7b6 to your computer and use it in GitHub Desktop.
Reverse Ruby Methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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