halving a string

S

Simon Strandgaard

On 2/2/07 said:
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"
 
R

Rob Biedenharn

On Feb 1, 2007, at 11:10 PM, Chris Shea wrote:
Good solutions already, but I had to chime in with one less clever
and without regexps.
I also didn't like "halve" as a name so I used "cleave".

Enjoy!

class String
def cleave
middle = self.length/2
early = self.rindex(' ', middle)
late = self.index(' ', middle)

[snip]

This is nice and versitle. One good augmentation might be...

def cleave(middle=nil)
middle ||= self.length/2

T.

That sounded good to me and so I did that and added support for
negative (from the end) offsets, too. And like String#[], it returns
nil if the desired cleavage position is outside the string.

def cleave(middle=nil)
middle ||= self.length/2
return nil unless (-self.length ... self.length).include?(middle)

middle += self.length if middle < 0

#...
end

-Rob

P.S. If anyone wants the full thing (with the new tests), email me
directly.

Rob Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,230
Messages
2,571,161
Members
47,794
Latest member
LucretiaEl

Latest Threads

Top