From: Chris Shea Date: 2007-02-02T15:20:08+09:00 Subject: Re: halving a string On Feb 1, 11:03 pm, Devin Mullins wrote: > Naive solution: > > class String > def halve(max_len=nil) > raise if max_len and size > max_len * 2 + 1 > space_indices = (0...size).find_all {|i| self[i] == ' '[0] } > splitter = space_indices.sort_by {|i| (i - size/2).abs }.first > if splitter.nil? || > (max_len && (splitter > max_len || size - splitter - 1 > max_len)) > [self[0...size/2], self[size/2..-1]] > else > [self[0...splitter], self[splitter+1..-1]] > end > end > end > > if __FILE__ == $0 > require 'test/unit' > > class SplitterTest < Test::Unit::TestCase > def test_stuff > assert_equal ['the frog', 'is green'], 'the frog is green'.halve > assert_equal ['ponchielli', 'wrote songs'], > 'ponchielli wrote songs'.halve > assert_raise(RuntimeError) { 'ab d'.halve 1 } > assert_nothing_raised { 'a b'.halve 1 } > assert_equal ['lizardman', 'lives'], 'lizardman lives'.halve > assert_equal ['lizardm', 'an lives'], 'lizardman lives'.halve(8) > assert_equal ['abcdef','ghijkl'], 'abcdefghijkl'.halve > end > end > end Yes. I see how expressions like space_indices.sort_by {|i| (i - size/ 2).abs }.first work, I just need to be able to think of them. It does what I really want (get the closest space to the middle of the string), instead of what I almost want (the last space in the first half of the string). Maybe I just gave up too early, or started barking up the wrong tree. I said, "I know, I'll use regular expressions" and then I had two problems. Thanks.