# Efficiency of string parsing

**URL:** <https://www.ruby-forum.com/t/efficiency-of-string-parsing/88550>\
**Category:** Ruby\
**Created:** [March 12, 2007, 4:25pm UTC](https://www.ruby-forum.com/t/efficiency-of-string-parsing/88550 "2007-03-12T16:25:56Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kev](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/e9bcb4/32.png) [@Kev](https://www.ruby-forum.com/u/Kev)\
**Post date:** [March 12, 2007, 4:25pm UTC](https://www.ruby-forum.com/t/efficiency-of-string-parsing/88550/1 "2007-03-12T16:25:56Z")

</div>

I have written a loop to basically parse a string, and at every 50th  
character check to see if is a space, if not, work back until it  
finds one, then insert a newline. I am turning masses of text (copy)  
from a DB into images, and I just wanted to automate it, I was just  
wondering if there are better ways of achieving what I am trying to  
do.

```
    characterCount = 0
    positionCount = 0
    insertPoint = MAX_LINE_LENGTH

    while characterCount != copy.length
      characterCount += 1
      positionCount += 1
      if positionCount == MAX_LINE_LENGTH
        begin
          characterCount -= 1
          insertPoint -= 1
        end until copy[characterCount].eql?(ASCII_SPACE)
        copy.insert(characterCount+=1,'\n')
        imageHeight += LINE_HEIGHT
        positionCount = 0
      end

    end

```

Cheers,  
Kev

---

<div class="post-metadata">

**Author:** ![Kev](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/e9bcb4/32.png) [@Kev](https://www.ruby-forum.com/u/Kev)\
**Post date:** [March 12, 2007, 4:30pm UTC](https://www.ruby-forum.com/t/efficiency-of-string-parsing/88550/2 "2007-03-12T16:30:57Z")

</div>

On 12.03.2007 16:23, Kev wrote:

> ```
> positionCount = 0
> end
> 
> end
> 
> ```

There are quite a lot of posts about word wrapping which seems what you  
are trying to do. You should be able to find them via the archives  
(Google G., ruby-talk archive).

A simplistic approach would probably do something like this:

str.gsub(/(.{1,50})\s+/, “\1\n”)

Kind regards

robert

---

<div class="post-metadata">

**Author:** ![Kev](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/e9bcb4/32.png) [@Kev](https://www.ruby-forum.com/u/Kev)\
**Post date:** [March 12, 2007, 5:27pm UTC](https://www.ruby-forum.com/t/efficiency-of-string-parsing/88550/3 "2007-03-12T17:27:06Z")

</div>

On 3/12/07, Robert K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> There are quite a lot of posts about word wrapping which seems what you  
> are trying to do. You should be able to find them via the archives  
> (Google G., ruby-talk archive).
> 
> A simplistic approach would probably do something like this:
> 
> str.gsub(/(.{1,50})\s+/, “\1\n”)

And here’s the start of a more sophisticated approach I just whipped up.

It uses split on a word boundary to split the string. It has some  
option keywords which allow preserving all whitespace, or only at the  
beginning of a line. If you don’t preserve all whitespace, it  
collapses whitespace within a line to a single space. If you don’t  
preserve whitespace at the beginning of a line, it elminates it,  
otherwise it keeps it as is. The default is to only preserve  
whitespace at the beginning of a line.

It does have a few bugs, which I didn’t bother addressing and leave as  
an exercise ot the reader.

1. It ignores existing new lines in the input string, which means that  
the next line will be short.

2. It keeps whitespace at the end of a line, as opposed to putting the  
newline after the last ‘word’.

## class String def wordwrap(linelength, kw\_args={}) keep\_all = kw\_args[:keep\_all] keep\_initial = keep\_all ||kw\_args[:keep\_initial] keep\_initial = true if keep\_initial.nil? current\_len = 0 split(/\b/).inject(“”) do | result, chunk | if current\_len + chunk.length \>= linelength result \<\< “\n” current\_len = 0 chunk = “” if chunk.strip.empty? unless keep\_initial else chunk = " " if chunk.strip.empty? unless keep\_all end current\_len += chunk.length result \<\< chunk end end end

Rick DeNatale

My blog on Ruby  
[http://talklikeaduck.denhaven2.com/](http://talklikeaduck.denhaven2.com/)

---

<div class="post-metadata">

**Author:** ![Kev](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/e9bcb4/32.png) [@Kev](https://www.ruby-forum.com/u/Kev)\
**Post date:** [March 12, 2007, 5:36pm UTC](https://www.ruby-forum.com/t/efficiency-of-string-parsing/88550/4 "2007-03-12T17:36:07Z")

</div>

Excellent sollution for coding efficiency. (though, I always think  
Regular Expressions should be commented well (broken into parts) due  
to the terseness of the syntax, especially for those who don’t use  
RegEx regularly. (no pun, really)

But would a Ruby iterator be faster?

Clearly this is a tool to wrap text to 50 characters per line without  
breaking words. Curious to see more ideas/approaches on that.

---

<div class="post-metadata">

**Author:** ![Kev](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/e9bcb4/32.png) [@Kev](https://www.ruby-forum.com/u/Kev)\
**Post date:** [March 12, 2007, 6:03pm UTC](https://www.ruby-forum.com/t/efficiency-of-string-parsing/88550/5 "2007-03-12T18:03:11Z")

</div>

On Mar 12, 2007, at 12:35 PM, John J. wrote:

> Excellent sollution for coding efficiency. (though, I always think  
> Regular Expressions should be commented well (broken into parts)  
> due to the terseness of the syntax, especially for those who don’t  
> use RegEx regularly. (no pun, really)
> 
> But would a Ruby iterator be faster?

I’m just curious what it is about Ruby iterators (I assume you mean  
methods like ‘each’) that you’d expect them to be more efficient than  
the gsub?

Tom

---

<div class="post-metadata">

**Author:** ![Kev](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/e9bcb4/32.png) [@Kev](https://www.ruby-forum.com/u/Kev)\
**Post date:** [March 12, 2007, 6:37pm UTC](https://www.ruby-forum.com/t/efficiency-of-string-parsing/88550/6 "2007-03-12T18:37:16Z")

</div>

On Mar 13, 2007, at 2:02 AM, Tom P. wrote:

> > But would a Ruby iterator be faster?
> 
> I’m just curious what it is about Ruby iterators (I assume you mean  
> methods like ‘each’) that you’d expect them to be more efficient  
> than the gsub?

Iterators/callbacks using Ruby code blocks whatever.  
Never said I expect them to be faster.  
I was asking.  
I don’t know how much text is being parsed. I do assume it is  
unstructured and not indexed in any manner.  
I’m just wondering if there isn’t more to know about why and what for  
in order to reach the best solution for the situation.  
Like they say in Perl… there’s more than 1 way right? Some ways are  
just interesting, some are fast, some are useful, etc…

---

<div class="post-metadata">

**Author:** ![Kev](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/e9bcb4/32.png) [@Kev](https://www.ruby-forum.com/u/Kev)\
**Post date:** [March 12, 2007, 7:05pm UTC](https://www.ruby-forum.com/t/efficiency-of-string-parsing/88550/7 "2007-03-12T19:05:20Z")

</div>

Had to take a swipe 9^)

class String  
def wrap(wrap\_col)  
retStr = self.dup  
start = 0  
while retStr[start,wrap\_col].length \>= wrap\_col  
ws\_pos = retStr[start,wrap\_col].rindex(" ")  
break if ws\_pos.nil?  
retStr[ws\_pos+start] = “\n”  
start += ws\_pos+1  
end  
retStr  
end  
end

Cheers  
Chris

---

<div class="post-metadata">

**Author:** ![Kev](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/e9bcb4/32.png) [@Kev](https://www.ruby-forum.com/u/Kev)\
**Post date:** [March 13, 2007, 9:40am UTC](https://www.ruby-forum.com/t/efficiency-of-string-parsing/88550/8 "2007-03-13T09:40:33Z")

</div>

On 12 Mar, 16:25, “Rick DeNatale” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ## And here’s the start of a more sophisticated approach I just whipped up. an exercise ot the reader. keep\_initial = keep\_all ||kw\_args[:keep\_initial] current\_len += chunk.length result \<\< chunk end end end
> 
> Rick DeNatale
> 
> My blog on Rubyhttp://talklikeaduck.denhaven2.com/

Being new to Ruby thats a great piece of code to get my head around,  
thanks all for suggestions thoughts and ideas 🙂
