Linking text with regex

Hi

This is probably a silly question, but I’m wondering what the best way
is to scan a string for regular expression matches, and then link to it.
It would be great to do it in one line, like this:

<% text.sub!(/#[-'A-Za-z]+/, link_to($&, tweet.category_name))%>

But as the sub! has not completed, $& still refers to the old variable.
I suppose I can just find the text I will be matching ahead of time,
which would involve scanning the string twice, but there might be a
better way. Thoughts?

Thanks in advance!!
–Peter

On Mon, Aug 10, 2009 at 11:14 AM, Peter E.[email protected]
wrote:

which would involve scanning the string twice, but there might be a
better way. Thoughts?

text.sub!(/#[-'A-Za-z]+/) {|m| link_to(m, tweet.category_name))}


Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

aha! This works great!

One further question - is there a best way to link the second and first
occurrences of the string differently? The only way I can think of is
with an index and a conditional in the block, but that just seems awful.

Thanks!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs