From: Rob Biedenharn Date: 2007-02-03T09:49:47+09:00 Subject: Re: halving a string On Feb 2, 2007, at 12:52 PM, Trans wrote: > On Feb 2, 10:55 am, Rob Biedenharn > wrote: >> 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 Rob@AgileConsultingLLC.com