Mike Stok wrote in post #1136321:
> On Feb 11, 2014, at 12:03 AM, Arup Rakshit <lists / ruby-forum.com> wrote:


> Where did the second "foo" go?

If there is a duplicate match, I am interested to take only the first one. So last "foo" is not desired.

>> With gsub how can I do that?
> I dont understand what you are trying to do. If you want to "ignore" the
> stuff which currently ends up in $` you need to match it as gsub
> replaces what was matched. For example:
>
> ~  pry
> [1] pry(main)> a = 'foo bar baz 12 34 ret'
> => "foo bar baz 12 34 ret"
> [2] pry(main)> token_re = Regexp.union(a.split(" "))
> => /foo|bar|baz|12|34|ret/
> [3] pry(main)> b = '2.bar foo tree ream baz foo'
> => "2.bar foo tree ream baz foo"
> [4] pry(main)> b.gsub(/.*?(#{token_re})/, '\1')
> => "barfoobazfoo"

This makes sense. Just need to remove the last "foo" that's a challenge. Also I can put space with some change in the `'\1'` to `' \1'`.

>
> If you just want a list of tokens matched then I wouldn't use gsub:
>
> [5] pry(main)> b.scan(token_re).join(' ')
> => "bar foo baz foo"
>
> and if you just want unique tokens matched:
>
> [8] pry(main)> b.scan(token_re).uniq.join(' ')
> => "bar foo baz"


I know, but this causes performance issue, if you do benchmark, then you can see. My mistake I didn't show you that attempt from my side. I wrote it first, then tried to thinking using `gsub`.