gsub!(/gsub!\('.'/, 'tr!(')
I do wish people would consider tr more often. I often see gsub! used to replace one character with another. Think of the electrons!
It’s particularly irksome when good tr usage is mixed with gsub seemingly at random. Take activesupport for example, in underscore:
def underscore(camel_cased_word)
camel_cased_word.to_s.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
Ok, great. gsub used for regular expressions, tr used to swap specific characters.
But then only a couple of lines down dasherize:
def dasherize(underscored_word)
underscored_word.gsub(/_/, '-')
end
So not only are they using gsub when tr is just fine, they are using a regex to match one specific character!
require 'benchmark'
Benchmark.bm do |x|
x.report { 5000.times { 'foo'.gsub!(/o/, 'a') } }
x.report { 5000.times { 'foo'.gsub!('o', 'a') } }
x.report { 5000.times { 'foo'.tr!('o', 'a') } }
end
# user system total real
# 0.020000 0.000000 0.020000 ( 0.022773)
# 0.020000 0.000000 0.020000 ( 0.020187)
# 0.010000 0.000000 0.010000 ( 0.004904)
I have submitted a lighthouse ticket.