Method: Integer#to_base

Defined in:
lib/epitools/core_ext/numbers.rb

#to_base(base = 10) ⇒ Object

Convert a number into a string representation (encoded in a base <= 64).

The number is represented usiing the characters: 0..9, A..Z, a..z, _, -

(Setting base to 64 results in the encoding scheme that YouTube and url shorteners use for their ID strings, eg: www.youtube.com/watch?v=dQw4w9WgXcQ)



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/epitools/core_ext/numbers.rb', line 310

def to_base(base=10)
  raise "Error: Can't handle bases greater than 64" if base > 64

  n        = self
  digits   = []
  alphabet = BASE_DIGITS[0...base]

  if bits = SMALL_POWERS_OF_2[base]
    # a slightly accelerated version for powers of 2
    mask   = (2**bits)-1

    loop do
      digits << (n & mask)
      n = n >> bits

      break if n == 0
    end
  else
    # generic base conversion
    loop do
      n, digit = n.divmod(base)
      digits << digit

      break if n == 0
    end
  end

  digits.reverse.map { |d| alphabet[d] }.join
end