From: Daniel Berger Date: 2003-07-16T03:56:48+09:00 Subject: Re: += vs << when appending arrays to an array Doug Beaver wrote: > > hello, > > i'm looking for a nice idiomatic way to append to an array. i'm porting > some encryption code from C to ruby, i don't have the code in front of > me but a relevant example is below: > > def translate(str="") > ret = [] > str.each_byte { |byte| ret << byte } > ret > end First, use unpack(). It's faster. def translate(str="") str.unpack("C*") end > > bytes = [] > bytes << translate("foo") > bytes += translate("foo") > > p bytes > > i'm using ruby 1.6.8, btw... I couldn't get it to work with << the way that you describe. You have a couple of options. First, use the splat operator with push(): e.g. push(*translate("foo")). Another option is to just call bytes.flatten! when you're done storing stuff within the bytes array. I think the only way to get this to work would be to convince Matz that << should accept multiple arguments, the same as push(). Then you could do: bytes << *translate("foo") Regards, Dan