David Miller
2/28/2008 4:52:00 AM
Joel VanderWerf wrote:
> Consultant1guru@hotmail.com wrote:
>> On Feb 26, 8:46 am, Dave M <dmil...@tecolote.net> wrote:
>>> Hello all
>>>
>>> I would like to convert integers to strings in a way that I haven't come
>>> across in the Ruby functions I have looked at. I would like the string
>>> to be exactly what the integer would be if I read it in from a binary file.
>>>
>>> In other words, the integer 0x61626364 would be the string "abcd" after
>>> the conversion. I can write code to do it, but I think there is
>>> probably a better way than the approach I have come up with.
>>>
>>> This works but seems very brute force to me:
>>>
>>> # assumes 32 bit numbers.
>>> class Bignum
>>> def to_ls
>>> i = self
>>> s = ""
>>> 4.times { s.concat(i & 0xff); i >>= 8}
>>> return s.reverse
>>> end
>>> end
>>>
>>> puts 0x61626364.to_ls
>>> abcd
>>>
>>> Also, it seems that I need this for both Bignum and Fixnum to cover the
>>> entire 32 bit number range.
>>>
>>> Thanks
>>>
>>> Dave M
>> Dave --
>>
>> I'm afraid that you may have selected the incorrect language for the
>> task at hand. Your question implies that you are doing some complex
>> parsing or homogenization, and Ruby, while a nice scripting language
>> for small tasks, is simply not a good choice for that application. If
>> you want to do simple web development or a little scraping, Ruby is
>> good for that, but that's about the extent of what it can really
>> handle well.
>>
>> I suggest you look at Perl or TCL for a serious scripting language,
>> Java for a robust programming language, and Visual Basic if you want
>> an ultra-fast development environment. These are tools that can
>> handle the task you describe in a sensible way.
>>
>> I am not saying that you should give up Ruby. Ruby is great for
>> learning some of the object-oriented concepts that while interesting,
>> may not be practical for some tasks in the real world.
>>
>> Hope that helps
>>
>> Cheers
>>
>> G
>
> Please reconsider your assessment of ruby, G.
>
> [0x61626364].pack("N")
>
> This returns the string "abcd" and does so elegantly and efficiently.
>
> In my experience and that of many others on this mailing list, ruby can
> be used for a variety of complex tasks, and not just web apps. Also,
> like perl, it makes simple tasks simple.
>
Thanks for the response to both Cliff and Joel. As I suspected, there
was a simple answer right in front of my nose -- I just didn't see it.
Your help is much appreciated.
As to "G", all I have to say is umm ... Thanks for nothing.
Dave M