How to split string by x bytes?

I have big string.
I want to get array of parts of strings (each 256 bytes).
What method is faster?

···

--
Posted via http://www.ruby-forum.com/.

Now I have this:

packets = (data.size.to_f / 256).ceil
packets.times do |packet|
  socket.write data[packet..(packet+256)]
end

And this is very ugly :frowning:

···

--
Posted via http://www.ruby-forum.com/.

string.scan /.{256}/

martin

···

On Thu, Feb 10, 2011 at 3:39 PM, Yan Bernacki <releu@me.com> wrote:

I have big string.
I want to get array of parts of strings (each 256 bytes).
What method is faster?

I don't know if this is the fastest but....
You could try unpack.
Modify it the way you want.

str = "abcdefghijklmnopq"
p str.unpack("a3"*(str.size/3))

Harry

···

On Thu, Feb 10, 2011 at 7:09 PM, Yan Bernacki <releu@me.com> wrote:

I have big string.
I want to get array of parts of strings (each 256 bytes).
What method is faster?

--

Thanks!

···

--
Posted via http://www.ruby-forum.com/.

Thanks! It is great :slight_smile:

···

--
Posted via http://www.ruby-forum.com/.

Yeah! It is greate :smiley:

···

--
Posted via http://www.ruby-forum.com/.

Martin DeMello wrote in post #980786:

I have big string.
I want to get array of parts of strings (each 256 bytes).
What method is faster?

string.scan /.{256}/

martin

Unpack is much faster. I have a string method which does something
similar

class String
  def to_2d_array(value)
    unpack("a#{value}"*((size/value)+((size%value>0)?1:0)))
  end
end

That enables me to do things like

string="123456789"
str_array=(string*1000).to_2d_array(256)
str_array.size => 36
str_array[0].size => 256
str_array[-1].size => 40
(36-1)*256+40 => 9000

And in benchmarks:

require 'benchmark'
Benchmark.measure { ("0"*10000000).scan(/.{256}/) } => 0.5700 0.0000
0.5700 (0.580)
Benchmark.measure { ("0"*10000000).unpack("a"*256)} => 0.0000 0.0000
0.0000 (0.004)

Mac
Mac

···

On Thu, Feb 10, 2011 at 3:39 PM, Yan Bernacki <releu@me.com> wrote:

--
Posted via http://www.ruby-forum.com/\.