Created
February 13, 2014 10:23
-
-
Save shunirr/8972838 to your computer and use it in GitHub Desktop.
自由に n 進数作る
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# -*- coding: utf-8 -*- | |
class CustomBaseNum | |
def self.convert(value, base_str) | |
base = base_str.size | |
result = '' | |
while true | |
break if value <= 0 | |
remainder = value % base | |
value /= base | |
result.insert 0, base_str[remainder] | |
end | |
result | |
end | |
end | |
class Bignum | |
alias :original_to_s :to_s | |
def to_s(arg) | |
if arg.is_a? String | |
CustomBaseNum.convert self, arg | |
else | |
original_to_s arg | |
end | |
end | |
end | |
class Fixnum | |
alias :original_to_s :to_s | |
def to_s(arg) | |
if arg.is_a? String | |
CustomBaseNum.convert self, arg | |
else | |
original_to_s arg | |
end | |
end | |
end | |
p 10000000.to_s('01') | |
p 10000000.to_s(2) | |
p 10000000.to_s('0123456789') | |
p 10000000.to_s(10) | |
p 10000000.to_s('0123456789abcdef') | |
p 10000000.to_s(16) | |
p 10000000.to_s('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') | |
p 100000000000000000000000000000.to_s('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment