On 2/2/07, Chris Shea <cmshea / gmail.com> wrote:
[snip]
> I have a feeling there's a one-line regexp that can do this. Am I
> right? If not, is there a better way?

no big regexp here

def half(s, threshold)
  l = s.size / 2
  0.upto([threshold, l].min) do |i|
    (l -= i; break) if s[l-i, 1] =~ /\s/
    (l += i; break) if s[l+i, 1] =~ /\s/
  end
  s.dup.insert(l, "\n").gsub(/^\s+|\s+$/, '')
end

ary = [
  "abcd efgh ijkl",
  "abcdef",
  "hello world",
  "aasd laksjd  asdj asjkd asdj jlas d",
  "foo bar ajd as dashd kah sdhakjshd ahdk ahsd asjh",
  "It's the end of the world as we know it",
  "If you didn't know any better you'd think this was magic.",
  "lizardman lives",
  "ponchielli wrote songs",
  "NSIntersectionRect YES NO"
]

ary.each{|s| p half(s, 6) }
p '---------------------'
ary.each{|s| p half(s, 2) }



output below:

"abcd efgh\nijkl"
"abc\ndef"
"hello\nworld"
"aasd laksjd  asdj\nasjkd asdj jlas d"
"foo bar ajd as dashd kah\nsdhakjshd ahdk ahsd asjh"
"It's the end of the\nworld as we know it"
"If you didn't know any better\nyou'd think this was magic."
"lizardman\nlives"
"ponchielli\nwrote songs"
"NSIntersectionRect\nYES NO"
"---------------------"
"abcd efgh\nijkl"
"abc\ndef"
"hello\nworld"
"aasd laksjd  asdj\nasjkd asdj jlas d"
"foo bar ajd as dashd kah\nsdhakjshd ahdk ahsd asjh"
"It's the end of the\nworld as we know it"
"If you didn't know any better\nyou'd think this was magic."
"lizardman\nlives"
"ponchielli\nwrote songs"
"NSIntersecti\nonRect YES NO"


-- 
Simon Strandgaard
http://opcoders.com/