From: Daniel Berger Date: 2003-05-06T22:51:26+09:00 Subject: Re: Suggestion: String#pack Brian Candler wrote: > > On Tue, May 06, 2003 at 01:55:51PM +0900, Austin Ziegler wrote: > > I have been working on some code recently where it would be very > > useful to do: > > > > "abcdef".pack(...) > > > > Instead, I have to do: > > > > ["abcdef"].pack(...) > > > > This is guaranteed to be at least a minor inefficiency because a > > temporary anonymous array needs to be created. Is there a good reason > > why String can't have a #pack method that Does The Right Thing? > > Well, there are many other data types that you might want to pack (Fixnum > and Bignum for example). Should they have a #pack method as well? A common > example is packing integers into 4-byte strings: > > [1234].pack("N") # OK > > 1234.pack("N") # ?? > > This becomes a bit like 'to_yaml' where ultimately everything has this > method, including Object, which I don't really like. Maybe it would be > better to turn it around and make module methods for packing individual > items: e.g. > > Pack.pack(1234,"N") > or > Pack.n4(1234) # network byte order, 4 bytes > > Hmm, lots of methods though. > > If you don't care about the slight inefficiency and just want the cleaner > interface, how about: > > class Object > def pack(arg) > [self].pack(arg) > end > end > > Regards, > > Brian. I had a similar idea a while ago: http://www.rubygarden.org/article.php?sid=249 Be sure to read the comments. Anyone want to submit a new RCR? Regards, Dan -- p ["010100101010111011001110001011100000010010000010011101101111011000101110000101101010011001001110000001000100101010101110010001101001111000000100000100101000011011000110110101101010011001001110"].pack("b*")