Stuart Clarke wrote:
> Hi all,
> 
> I am having trouble working out some logic for my problem. I basically
> have a long string (320 characters) and I want to split into smaller
> strings no longer than 50 characters in length. At present I have the
> following regex:
> 
> data = "big long string"
> 
> puts data.scan(/{50}/)
>

error: invalid regular expression; there's no previous pattern, to which 
'{' would define cardinality


data =<<ENDOFSTRING
Hello world.  Hello moon.
Goodbye world. Goodbye moon.

Hello world.  Hello moon.
Goodbye world. Goodbye moon.
The end.
ENDOFSTRING

chunks = []
curr_chunk = []
curr_length = 0

data.scan(/.+?\b/m) do |word|
  wlen = word.length

  if curr_length + wlen <= 50
    curr_chunk << word
    curr_length += wlen
  else
    chunks << curr_chunk.join()
    curr_chunk = [word]
    curr_length = wlen
  end
end

if curr_chunk.length > 0
  chunks << curr_chunk.join()
end

p chunks

chunks.each do |chunk|
  puts chunk.length
end

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