12

特定のサイズに従って、文字列をチャンクに分割する必要があります。チャンク間で単語を分割することはできないため、次の単語を追加するとチャンク サイズを超えて次の単語を開始するタイミングをキャッチする必要があります (チャンクが指定されたサイズよりも小さくても問題ありません)。

これが私の作業コードですが、これを行うためのよりエレガントな方法を見つけたいと思います。

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
4

2 に答える 2

22

どうですか:

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)."]

@sawa コメント後の更新:

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

\W で終わる文字列を必要としないため、これは優れています。

また、指定された長さよりも長い単語を処理します。実際にはそれらを分割しますが、これは望ましい動作だと思います

于 2013-03-14T04:48:42.847 に答える
5

@Yuriy、あなたの交代は問題のようです。どうですか:

str.scan /\S.{1,24}(?!\S)/
#=> ["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)."]
于 2013-03-14T10:20:51.483 に答える