Skip to content

Instantly share code, notes, and snippets.

@gleicon
Forked from juanplopes/base_62.rb
Created March 26, 2012 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gleicon/2209621 to your computer and use it in GitHub Desktop.
Save gleicon/2209621 to your computer and use it in GitHub Desktop.
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
Copy link
Author

gleicon commented Mar 26, 2012

fiz uma versão com monkey patch :D

@juanplopes
Copy link

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