This isn't specifically useful in any RM project, but we don't have a raw coding board so why not post it here?
This arose as a challenge from a brother, as we were discussing what 1 + 1 could equate to depending on what the base is or the format of the question, i.e. in normal base 10 it is simply 2, in base 2 it is 10 (funny how that works out) and if the question is posed in string format, '1' + '1' = '11'.
Now, because I am a recluse and I have nothing better to do with my time, I whipped up a massive chunk of code that could convert numbers from several bases. Then I realized that Ruby is awesome and already
has methods that can do that, whacked my head several times, and concocted a much smaller chunk of code to do it. Essentially, it's just a method that calls built-in methods that do it, but made much simpler. The base method is:
string.to_i(from).to_s(to)
Where string is a string containing a number in any base, from is the base that string is in, and to is the base you'd like it to be converted to.
So I made a simple method in the string class that would do this for convenience's sake.
class String
def convert_base(from, to)
self.to_i(from).to_s(to)
end
end
Then I realized that it didn't like converting things to base 1 (which is ridiculous anyway) so I made a very simple branch to fix that:
if to == 1
n = self.to_i(from).to_s(10).dup
s = ''
n.to_i.times do s += '1' end
return s
end
Which worked fine, until I noticed it didn't like converting things
from base 1 either.
if from == 1
return self.size.to_s(to)
end
And that fixed that problem. I haven't found any other problems yet, so my final, 14-line snippet is:
class String
def convert_base(from, to)
if from == 1
return self.size.to_s(to)
end
if to == 1
n = self.to_i(from).to_s(10).dup
s = ''
n.to_i.times do s += '1' end
return s
end
self.to_i(from).to_s(to)
end
end
And I'm proud of it
I just wanted to share it
Thank you.