# Using gsub to replace text with link from database

**URL:** <https://www.ruby-forum.com/t/using-gsub-to-replace-text-with-link-from-database/184520>\
**Category:** Rails\
**Created:** [March 3, 2010, 7:41pm UTC](https://www.ruby-forum.com/t/using-gsub-to-replace-text-with-link-from-database/184520 "2010-03-03T19:41:31Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![allanium](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/9f8e36/32.png) [@allanium](https://www.ruby-forum.com/u/allanium)\
**Post date:** [March 3, 2010, 7:41pm UTC](https://www.ruby-forum.com/t/using-gsub-to-replace-text-with-link-from-database/184520/1 "2010-03-03T19:41:31Z")

</div>

I’m really close to solving this that I can smell it. In a nutshell I’m  
trying to create this:

> **[Link to Sports Reference Pages | Baseball-Reference.com](https://www.baseball-reference.com/friv/link_players.cgi)**
>
> Use the Sports Reference linker to link player names in your articles and we'll link back to you from those player pages.

I have an app that has a database of baseball players.  
I’m trying to create a feature where you can copy and paste your blog  
text, the feature will scan the text and return the text with the  
proper html links of my app that point to the player. For example, I’m  
a blog writer, I create a entry with one sentence “I am a big fan of  
Derek Jeter and Jorge Posada of the Yankees” and I click submit. I want  
the output to return the same sentence, but with the link of Derek Jeter  
and Jorge Posada.

This is where I’m at:  
#This code is taking the sentence and scanning it for two words that  
are next to each other that have the first letter capitalized  
@new\_link\_array = #this is the link data that is returned from my query  
search via ferret. It will provide the proper link to the players.  
@full\_text = params[:q]  
@full\_text\_array = @full\_text.scan(/([A-Z]+[a-zA-Z]\* [A-Z]+[a-zA-Z]\*)/)

@full\_text\_array.each\_with\_index do |original\_name, i|  
@full\_text.gsub!(original\_name.to\_s, @new\_link\_array[i])  
end

results = @full\_text.scan(/([A-Z]+[a-zA-Z]\* [A-Z]+[a-zA-Z]\*)/)

names\_links = {}

results.each do |name|  
unless names\_links[name]  
names\_links[name] = method\_to\_construct\_link\_for\_name(name)  
end  
end

names\_links.each\_pair do |name, link|  
@full\_text.gsub!(name, link)  
end

The results are not consistent. I was wondering if somebody could help  
me out.

-A
