Skip to content

Instantly share code, notes, and snippets.

@mvidner mvidner/digits.rb
Created Sep 20, 2010

Embed
What would you like to do?
#! /usr/bin/env ruby
# in ruby 1.8, Enumerator is limited
require 'generator'
# 1234 -> [1, 2, 3, 4]
# but don't use a String
def digits(i, base = 10)
g = Generator.new do |g|
begin
dm = i.divmod(base)
g.yield dm.last
i = dm.first
end until i.zero?
end
g.to_a.reverse
end
p digits(0755)
# => [4, 9, 3]
p digits(0755, 8)
# => [7, 5, 5]
@EskiMag

This comment has been minimized.

Copy link

commented Sep 20, 2010

def digits(i, base = 10)
  ret = []
  while i > 0
    ret << i % base
    i /= base
  end
  ret.reverse
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.