Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance implications of string#gsub chains?

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

For example, here's an example of a method from the 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 app, I want it to change underscores or hyphens to a space, so I want to add a gsub method at the end:

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

Does that raise red flags with regard to performance or style?

like image 288
nickcoxdotme Avatar asked Feb 17 '23 14:02

nickcoxdotme


1 Answers

str.tr('-_', ' ') 

is worth considering (doc)

like image 65
steenslag Avatar answered Feb 27 '23 16:02

steenslag