Splitting a string into variable word numbers

The following question was posted by @ruhroe about an hour ago. I was about to post an answer when it was filmed. This is unfortunate, as I thought it was quite interesting. I will return it in case the OP sees this, and also provide others with the opportunity to publish solutions.

The original question (which I edited):

The problem is to split the line into some spaces in the line based on criteria that partially depend on the number set by the user. If this number were, say, 5, each substring would contain:

  • one word with 5 or more characters or
  • as many consecutive words (separated by spaces) as possible, if the resulting line has no more than 5 characters.

For example, if the line was:

"abcdefg fg hijkl mno pqrs tuv wx yz"

the result will be:

["abcdefg", "fg", "hijkl", "mno", "pqrs", "tuv", "wx yz"]
  • "abcdefg" , .
  • "fg" , "fg" 5 , , "fg hijkl" 5 .
  • "hijkl" , .

?

+4
2

( ), , :

  • ,
  • ,
  • , ,

- ( - . ):

words.each do |word|
  if line.blank?
    # this is a new line, so start it with the current word
    line << word
  elsif word_can_fit_line?(line, word, length)
    # the word fits, so append it to the current line
    line << " #{word}"
  else
    # the word doesn't fit, so keep this line and start a new one with
    # the current word
    lines << line
    line = word
  end
end

# add the last line and we're done
lines << line

lines

, word_can_fit_line? - , , , .

+1

, :

str = "abcdefg fg hijkl e mn pqrs tuv wx yz"

str.scan(/\b(?:\w{5,}|\w[\w\s]{0,3}\w|\w)\b/)
  #=> ["abcdefg", "fg", "hijkl", "e mn", "pqrs", "tuv", "wx yz"] 
+3

All Articles