Ruby integer to string key
Posted
by
Gene
on Stack Overflow
See other posts from Stack Overflow
or by Gene
Published on 2012-11-26T16:53:18Z
Indexed on
2012/11/26
17:03 UTC
Read the original article
Hit count: 197
A system I'm building needs to convert non-negative Ruby integers into shortest-possible UTF-8 string values. The only requirement on the strings is that their lexicographic order be identical to the natural order on integers.
What's the best Ruby way to do this?
We can assume the integers are 32 bits and the sign bit is 0. This is successful:
(i >> 24).chr + ((i >> 16) & 0xff).chr + ((i >> 8) & 0xff).chr + (i & 0xff).chr
But it appears to be 1) garbage-intense and 2) ugly. I've also looked at pack
solutions, but these don't seem portable due to byte order.
FWIW, the application is Redis hash field names. Building keys may be a performance bottleneck, but probably not. This question is mostly about the "Ruby way".
© Stack Overflow or respective owner