Robert Klemme
8/20/2008 5:20:00 AM
On 19.08.2008 22:33, Rob Biedenharn wrote:
> On Aug 19, 2008, at 4:08 PM, Pål Bergström wrote:
>
>> This seems to do the trick. Will it always work?
>>
>> lastspace = message.message[0..70].rindex(" ")
>> puts message.message[0..lastspace.to_i]
>
>
> You likely want an exclusive range unless you want the space at the end.
>
> message.message[0...lastspace.to_i]
>
> What if there's no space? Then perhaps:
>
> message.message[0..(lastspace || -1).to_i]
>
> Of course, that puts you back in the position of getting the full
> string rather than some truncated version with no more than your
> desired number of characters.
Pal, it seems we haven't seen the complete specification of what you
want to do. It seems that not only length is a condition but also
positions of spaces.
I get the feeling that a solution using regular expressions might be
more efficient and also easier in your case. Maybe any of
str.sub! %r{\A(.{50}).*\z}, '\\1'
str.sub! %r{\A(.{1,50})(?: .*)?\z}, '\\1'
str.sub! %r{\s\S*\z}, ''
Depends on your string contents of course.
Kind regards
robert