Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
base 62 encoding in ruby (versão devops)
# 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
@gleicon

This comment has been minimized.

Copy link
Owner Author

@gleicon gleicon commented Mar 26, 2012

fiz uma versão com monkey patch :D

@juanplopes

This comment has been minimized.

Copy link

@juanplopes juanplopes commented Mar 26, 2012

versão funcional com monkey patch:

https://gist.github.com/2209752

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment