binarymason
binarymason

Reputation: 1433

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

Upvotes: 3

Views: 146

Answers (2)

Cary Swoveland
Cary Swoveland

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

falsetru
falsetru

Reputation: 369124

How about using String#tr:

'Strings'.tr('sS', 'zZ')
# => "Ztringz"

Upvotes: 4

Related Questions