Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Forked from gleicon/base_62.rb
Created March 26, 2012 21:11
Show Gist options
  • Save juanplopes/2209752 to your computer and use it in GitHub Desktop.
Save juanplopes/2209752 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()
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
@gleicon
Copy link

gleicon commented Mar 26, 2012

<3

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