# Passing a block to gsub

**URL:** <https://www.ruby-forum.com/t/passing-a-block-to-gsub/185249>\
**Category:** Rails\
**Created:** [March 16, 2010, 9:21pm UTC](https://www.ruby-forum.com/t/passing-a-block-to-gsub/185249 "2010-03-16T21:21:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![perezda](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/46a35a/32.png) [@perezda](https://www.ruby-forum.com/u/perezda)\
**Post date:** [March 16, 2010, 9:21pm UTC](https://www.ruby-forum.com/t/passing-a-block-to-gsub/185249/1 "2010-03-16T21:21:23Z")

</div>

Hello,

So I have a product description field and in that product description  
field every time I have the @ symbol followed by a product id the  
following method will replace the @ sign with the products permalink  
in a format. The code below works.

def product\_description(product)  
product.description.gsub(/@(\w+)/m) do |w|  
ws = Product.find\_by\_id("#{$1}")  
%{}  
end  
end

However now I want to be able to be able to give it two options, the @  
and the @c. the @ sign will associate it with a product id and the @c  
will associate it with a category id. So I tried the following bellow  
but I can only get one or the other to work, I can not get them to  
work at the same time.

def product\_description(product)  
product.description.gsub(/@(\w+)/m) do |w|  
ws = Product.find\_by\_id("#{$1}")  
%{}  
end  
product.description.gsub(/@c(\w+)/m) do |w|  
ws = Category.find\_by\_id("#{$1}")  
%{}  
end  
end

If anyone has some suggestions I would greatly appreciate it. Thanks  
in advance.

---

<div class="post-metadata">

**Author:** ![perezda](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/46a35a/32.png) [@perezda](https://www.ruby-forum.com/u/perezda)\
**Post date:** [March 17, 2010, 8:32pm UTC](https://www.ruby-forum.com/t/passing-a-block-to-gsub/185249/2 "2010-03-17T20:32:38Z")

</div>

Well, I finally figured it out, might as well post it just in case  
anyone else is trying to do the same thing. Below is the code.

# converts @ signs into product links and category links

def product\_description(product)  
product.description.gsub(/@(\w+)/m) do |w|  
if #{$1} =~ /p(.\*)/  
wp = Product.find\_by\_id(“#{$1}”.delete “p”)  
%{}  
else  
wt = Taxon.find\_by\_id(“#{$1}”.delete “t”)  
%{[}  
end  
end  
end](https://www.ruby-forum.com/t/#{wt.permalink.chop})

[ 

Pretty much what this allows me to do is I can take a text field and  
automatically add links to words for example;

 ](https://www.ruby-forum.com/t/#{wt.permalink.chop})

[this is a test, this is a link to a @p30 product](https://www.ruby-forum.com/t/#{wt.permalink.chop}), and this is a  
link to a @t45 category

That way it makes my admin views a little bit cleaner and eventually I  
will add a rescue feature so if that product or category has been  
deleted i wont have any broken links through out the site.
