Martin DeMello wrote in post #980786:
> 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?
>
> 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

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