Created
January 11, 2010 10:09
-
-
Save rwoeber/274126 to your computer and use it in GitHub Desktop.
Ruby rot13
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
# or simply: | |
'foobar'.tr 'A-Za-z','N-ZA-Mn-za-m' | |
# rot(x) | |
class String | |
def rot(num = 13) | |
return self.split("").collect { |ch| | |
if /^[a-z]$/ === ch | |
((ch[0] + num - 'a'[0]) % 26 + 'a'[0]).chr | |
elsif /^[A-Z]$/ === ch | |
((ch[0] + num - 'A'[0]) % 26 + 'A'[0]).chr | |
else | |
ch | |
end | |
}.join("") | |
end | |
alias rot13 rot | |
end | |
p "foobar".rot(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"abc".rot(1) #=> "Abc"
@xfaider approach is simple and elegant.
I think this should work for a flexible approach:if you want amount to be higher than 26: