Implications for strings # gsub chains?

Are there any performance implications of the .gsub chain and / or .sub methods for a string in Ruby?

For example, here is an example of a method from a Rails source that creates an alt tag for images. It removes the file extension and digest (if any).

def image_alt(src) File.basename(src, '.*').sub(/-[[:xdigit:]]{32}\z/, '').capitalize end 

In my application, I want it to change underscores or hyphens to space, so I want to add the gsub method at the end:

 def image_alt(src) File.basename(src, '.*').sub(/-[[:xdigit:]]{32}\z/, '').gsub(/(_|-)/, ' ').capitalize end 

Does this raise red flags in terms of performance or style?

+4
source share
3 answers
 str.tr('-_', ' ') 

worth considering ( doc )

+7
source

I had no problem with this. I use multiple gsub calls in several of my programs and I did not have a performance issue. I would not worry about this in terms of performance. As for the style, I think it is a personal preference. Personally, I try to avoid regular expressions at all costs. But it's just me.

0
source

When regular expression matches in the chain should not overlap, then run them in the conditional expression under the same StringScanner iteration, and outputting the result to StringIO can improve performance.

0
source

All Articles