Created
April 21, 2015 16:15
-
-
Save mikecmpbll/e34c8cdd6ad2fc0c8747 to your computer and use it in GitHub Desktop.
Split a ruby string into X roughly even length lines, but don't break words.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def str_in_lines(str, x) | |
word_break_indices = [] | |
str.to_enum(:scan,/\b/).map do |m,| | |
word_break_indices << $`.size | |
end | |
perfect_split_indices = (0..str.length).step(str.length/x).to_a | |
actual_split_indices = perfect_split_indices.map{ |si| word_break_indices.min_by{ |wbi| (wbi - si).abs } } | |
actual_split_indices.push(str.length) unless actual_split_indices.last == str.length | |
actual_split_indices.each_cons(2).map do |si, ei| | |
str[si..ei-1] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment