miyohideの日記

技術的なメモなどを記しています

2023年4月27日

Rubyでfold

一定の長さで文字列を折りたたむことをやりたい。以下のgistを参考に。

gist.github.com

こんな感じで書いてみた。

class String
  def fold(length: 80)
    return self if self.length < length

    sep = "\\s"
    regexp = /((^[^#{sep}]{#{length - 1}})?(?(2)|^.{1,#{length - 2}}#{sep}))(.*)/
    _, folded, _, rest = *self.match(regexp)

    "#{folded}\n#{rest.fold(length: length)}"
  end
end

もうちょっと整理しよう。