On 7/19/06, Yohanes Santoso <ysantoso-rubytalk / dessyku.is-a-geek.org> wrote: > "David Balmain" <dbalmain.ml / gmail.com> writes: > > > On 7/19/06, Yohanes Santoso <ysantoso-rubytalk / dessyku.is-a-geek.org> wrote: > >> "David Balmain" <dbalmain.ml / gmail.com> writes: > >> > >> > Hey all, > >> > > >> > I need to come up with a way to encode an integer as a string so that > >> > it will sort correctly lexicographically. This is pretty easy when you > >> > have a fixed integer range but how do you do it with Ruby's BigNums? > >> > Any ideas? > >> > > >> > Cheers, > >> > Dave > >> > >> def encode_integer(num) > >> "x"*num > >> end > >> > >> Do I win something? > >> > >> YS. > > > > Nice idea :P > > But how about negative numbers. > > Same technique, but put them in different namespace. > > YS. I need to be able to compare positive integers with negative so I would need to add a bit to this technique, (not to mention a couple of terabytes of memory to handle even moderately large numbers :)) def encode_integer(int) if (int > 0) "z" * int else "x" * -int + "y" end end Anyway, here is a better solution using only only digits 0-9. I'll extend it myself to use the full ascii alphabet; def encode_int(int) if (int > 0) int_str = int.to_s ("3%04d" % int_str.size) + int_str elsif (int < 0) int_str = (-int).to_s ("1%04d" % (9999 - int_str.size)) + (10 ** (int_str.size + 1) + int).to_s else "2" end end Cheers, Dave