"Joel VanderWerf" <vjoel / PATH.Berkeley.EDU> schrieb im Newsbeitrag
news:3EF94358.7030703 / path.berkeley.edu...
> Rob wrote:
> > I have an array with the following elements:
> >
> > array[0] = "car"
> > array[1] = "bike"
> > array[2] = "motorcicle"
> > .......
> > array[n] = .........
> >
> > And I have a string with the following text.
> >
> > "Today I went to school by car. I saw............ "
> >
> > What I am trying to do is that everytime the program finds one of the
words
> > from the list in the text,
> > it will place an astherisc * to replace that word.
> >
> > But I cannot figure out how to do this because it is an array not a
regular
> > expression.
>
> You can interpolate it into a regex, but I don't know how well that
scales:
>
> array = []
> array[0] = "car"
> array[1] = "bike"
> array[2] = "motorcicle"
>
> string = "Today I went to school by car. I saw............ "
>
> p string.gsub(/#{array.join("|")}/o) {|s| "*" * s.size}

If you want to make sure you match words you'll have to do

p string.gsub(/\b(#{array.join("|")})\b/) {|s| "*" * s.size}

Better scaling for large arrays:

string.gsub( /\b(\w+)\b/ ) {|m| array.include?( m ) ? "*" * m.length : m }

One can optimize performance by changing the array into a hash and testing
for hash.has_key? instead of array.include?

    robert