From: Javier Fontan Date: 2002-03-04T19:23:23+09:00 Subject: Re: string to array and back Hello, You should use each_byte to iterate character by character in a string. If you want to create an array from a string something like this should work: tmp=[] string.each_byte { |byte| tmp.push(byte.chr) } to recreate a string newstring=tmp.join bye On Sun 03 Mar 2002 20:17, you wrote: > On Sun, 03 Mar 2002 18:36:25 GMT, Matt Armstrong wrote: > >Ron Jeffries writes: > >> I am needing to convert strings to arrays of bytes and back. I see > >> pack and unpack with argument of 'c*' will do it. Is there a better > >> way? > > > >A String is an array of bytes. Try doing no conversion at all. > > Actually, a string is /almost/ an array of bytes. That's what's standing in > my way at the moment. It seems to me that Ruby isn't quite as smooth and > symmetric as it could be here. > > In Ruby, an array of bytes is really an array of objects that behave like > Fixnum, if I'm not mistaken. Send it :each and you get the bytes one after > another. But a string mistakenly thinks that :each should deliver in lines, > not bytes. Gack. > > An array of bytes sent :to_a answers itself. A string sent :to_a answers, > get this, an array with the string in it. (Or lots of strings, if the > string has newlines in it.) Gack. > > So arrays of bytes and strings can't be used polymorphically, and they are > really difficult to use together. At the moment it looks like I'll have to > convert. Maybe I'll find another way. > > There must be a good, simple way to do what I'm up to. But I don't see it > yet. > > Ronald E Jeffries > http://www.XProgramming.com > http://www.objectmentor.com > I'm giving the best advice I have. You get to decide whether it's true for > you. -- Javier Fontan Mui�os jfontan@cesga.es CESGA, Supercomputing Center of Galicia