-
-
Save gleicon/2209621 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() | |
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" | |
return alphabet[0] if self == 0 | |
num = self | |
arr = [] | |
base = alphabet.size | |
while num > 0 do | |
rem = num % base | |
num = num / base | |
arr << alphabet[rem] | |
end | |
arr.reverse.join | |
end | |
end | |
class String | |
def from_base62() | |
string = self | |
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" | |
base = alphabet.size | |
strlen = string.size | |
num = 0 | |
idx = 0 | |
string.each_char do |char| | |
power = (strlen - (idx + 1)) | |
num += alphabet.index(char) * (base ** power) | |
idx += 1 | |
end | |
num | |
end | |
end | |
i = 4777 | |
c = "1F3" | |
puts i.to_base62 | |
puts c.from_base62 |
versão funcional com monkey patch:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fiz uma versão com monkey patch :D