-
-
Save juanplopes/2209752 to your computer and use it in GitHub Desktop.
base 62 encoding in ruby (versão devops)
This file contains 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
# monkey patch to have base62 encoding over Integers and Strings | |
class Integer | |
def to_base62() | |
char = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[self%62,1] | |
return char if self < 62 | |
return (self/62).to_base62 + char | |
end | |
end | |
class String | |
def from_base62() | |
idx = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".index(self[-1]) | |
return idx if self.size == 1 | |
return idx + self[0..-2].from_base62 * 62 | |
end | |
end | |
i = 4777 | |
c = "1F3" | |
puts i.to_base62 | |
puts c.from_base62 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
<3