This isn't specifically useful in any RM project, but we don't have a raw coding board so why not post it here? :Vg;
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
endThen 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)
endAnd 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
endAnd I'm proud of it :mad: I just wanted to share it :mad:
Thank you.
:bigmad:
Glad you didn't forget about unary :mad:
Anyway, I swear this has a use in RGSS3, I just forget what exactly.
It is small revelations like this which lead to the big breakthroughs. Well done.
Well done :3
Quote from: cozziekuns on March 12, 2012, 04:38:21 PM
Glad you didn't forget about unary :mad:
Anyway, I swear this has a use in RGSS3, I just forget what exactly.
I would never forget unary, the starting point of all mathematics :mad:
If you ever find out a usage for it, could you please tell me? I just did it because, there might've been a use that crossed my mind, but it escaped me :mad:
Thank you all.
:bigmad:
EDIT:: I did some testing and figured out that this snippet can convert from radices 1 to 36, as that is the highest base Ruby can handle, to my knowledge (ten digits + 26 letters). I also discovered you can use base 36 to make numbers say silly things. 'cucumber', for instance, when converted from base 36 to base 10, is 1006450463043. In case any of you needed to know that.