Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string into chunks of specified size without breaking words

Tags:

string

ruby

I need to split a string into chunks according to a specific size. I cannot break words between chunks, so I need to catch when adding the next word will go over chunk size and start the next one (it's ok if a chunk is less than specified size).

Here is my working code, but I would like to find a more elegant way to do this.

def split_into_chunks_by_size(chunk_size, string)
  string_split_into_chunks = [""]
  string.split(" ").each do |word|
    if (string_split_into_chunks[-1].length + 1 + word.length > chunk_size)
      string_split_into_chunks << word
    else
      string_split_into_chunks[-1] << " " + word
    end
  end
  return string_split_into_chunks
end
like image 850
psychickita Avatar asked Mar 14 '13 04:03

psychickita


1 Answers

How about:

str = "split a string into chunks according to a specific size. Seems easy enough, but here is the catch: I cannot be breaking words between chunks, so I need to catch when adding the next word will go over chunk size and start the next one (its ok if a chunk is less than specified size)." 
str.scan(/.{1,25}\W/)
=> ["split a string into ", "chunks according to a ", "specific size. Seems easy ", "enough, but here is the ", "catch: I cannot be ", "breaking words between ", "chunks, so I need to ", "catch when adding the ", "next word will go over ", "chunk size and start the ", "next one (its ok if a ", "chunk is less than ", "specified size)."]

Update after @sawa comment:

str.scan(/.{1,25}\b|.{1,25}/).map(&:strip)

This is better as it doesn't require a string to end with \W

And it will handle words longer than specified length. Actually it will split them, but I assume this is desired behaviour

like image 186
Yuri Golobokov Avatar answered Sep 30 '22 02:09

Yuri Golobokov