smarter character replacement using ruby gsub and regexp
        Posted  
        
            by agriciuc
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by agriciuc
        
        
        
        Published on 2010-04-20T19:50:49Z
        Indexed on 
            2010/04/20
            19:53 UTC
        
        
        Read the original article
        Hit count: 441
        
Hi guys!
I'm trying to create permalink like behavior for some article titles and i don't want to add a new db field for permalink. So i decided to write a helper that will convert my article title from:
"O "focoasa" a pornit cruciada, împotriva barbatilor zgârciti" to "o-focoasa-a-pornit-cruciada-impotriva-barbatilor-zgarciti".
While i figured out how to replace spaces with hyphens and remove other special characters (other than -) using:
title.gsub(/\s/, "-").gsub(/[^\w-]/, '').downcase
I am wondering if there is any other way to replace a character with a specific other character from only one .gsub method call, so I won't have to chain title.gsub("a", "a") methods for all the UTF-8 special characters of my localization.
I was thinking of building a hash with all the special characters and their counterparts but I haven't figured out yet how to use variables with regexps.
What I was looking for is something like:
title.gsub(/\s/, "-").gsub(*replace character goes here*).gsub(/[^\w-]/, '').downcase
Thanks!
© Stack Overflow or respective owner