Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String#gsub to maintain case?

When using gsub, is it possible to maintain case?

This is working example, possible to do this without calling gsub twice? Perhaps add case insensitive i to the regex?

 'Strings'.gsub(/s/, 'z').gsub(/S/, 'Z') #=> Ztringz

Goal (obviously doesn't work):

'Strings'.gsub(/s/i, 'z') #=> Ztringz
like image 535
binarymason Avatar asked Dec 01 '25 03:12

binarymason


1 Answers

How about using String#tr:

'Strings'.tr('sS', 'zZ')
# => "Ztringz"
like image 101
falsetru Avatar answered Dec 02 '25 20:12

falsetru