Skip to content

Instantly share code, notes, and snippets.

@dux
Last active August 29, 2015 14:03
Show Gist options
  • Save dux/be462728762cebf16b72 to your computer and use it in GitHub Desktop.
Save dux/be462728762cebf16b72 to your computer and use it in GitHub Desktop.
Encode any integer to string base of choice. Just replace keys with one you want to encode into. StringBase.encode(11111111) == "frgh"
module StringBase
KEYS = 'bcdfghjklmnpqrstvwxyz'
def self.encode( value )
ring = Hash[KEYS.chars.map.with_index.to_a.map(&:reverse)]
base = KEYS.length
result = []
until value == 0
result << ring[ value % base ]
value /= base
end
result.reverse.join
end
def self.decode( string )
ring = Hash[KEYS.chars.map.with_index.to_a]
base = KEYS.length
# Ruby < 2 string.reverse.chars.with_index.inject(0) do |sum,(char,i)|
string.reverse.chars.map.with_index.inject(0) do |sum,(char,i)|
sum + ring[char] * (base**i)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment