Reputation: 15107
I am currently using Ruby's 'base64' but the strings that are created have special characters like /+= .
How do I remove these and still make sure that my decode works in the future?
Essentially I want alphanumeric to be used.
Upvotes: 1
Views: 9364
Reputation: 84114
Rather than invent something new, I'd use Base64.urlsafe_encode64
(and its counterpart Base64.urlsafe_decode64
) which is basically base64 with + and / replaced with - and _. This conforms to rfc 4648 so should be widely understandable
Upvotes: 5
Reputation: 80065
class Integer
Base62_digits = [*("0".."9"), *("a".."z"), *("A".."Z")]
def base_62
return "0" if zero?
sign = self < 0 ? "-" : ""
n, res = self.abs, ""
while n > 0
n, units = n.divmod(62)
res = Base62_digits[units] + res
end
sign + res
end
end
p 124.base_62 # => "20"
This could be adapted to handle lower bases, but it may be sufficient as is.
Upvotes: 0
Reputation: 168071
If you want alphanumeric, I think it is better and is practical to use base 36. Ruby has built-in encoding/decoding up to base 36 (26 letters and 10 numbers).
123456.to_s(36)
# => "qglj"
"qglj".to_i(36)
# => 123456
Upvotes: 2