Reputation: 1433
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
Upvotes: 3
Views: 146
Reputation: 110685
Three ways to use String#gsub:
With a block and a simple conditional expression
'Strings'.gsub(/s/i) { |str| str=='s' ? 'z' : 'Z' }
#=> "Ztringz"
With a block and ASCII value offset
offset = 'z'.ord-'s'.ord
#=> 7
'Strings'.gsub(/s/i) { |str| (str.ord + offset).chr }
#=> "Ztringz"
The block could alternatively be written:
{ ($&.ord + offset).chr }
With a hash having a default value
'Strings'.gsub(/s/i, Hash.new { |_,k| k }.update('s'=>'z', 'S'=>'Z'))
#=> "Ztringz"
Upvotes: 2