Stacca
Stacca

Reputation: 831

Is it possible to do a case-insensitive `gsub`?

I am doing a gsub to swap "bad" for "good". Is there a way to use capitalize so it will swap both lower and upper case? Or will I have to write the def twice?

def add_more_ruby(string)
  string.gsub('bad','good').capitalize
end

Upvotes: 30

Views: 14761

Answers (2)

Dan
Dan

Reputation: 915

There is also the option to use the block form of gsub to handle different capitalisations differently:

string.gsub(/bad/i) do |match|
  match == 'Bad' ? 'Good' : 'good'
end

When the regexp matches, the block is executed, and the return value of the block is used as the replacement.

So this will replace 'Bad' with 'Good', and 'bad' written with any other permutation of capital and lower-case letters (including 'bad' but also 'BAD', 'bAD' etc) with 'good'.

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

You can pass Regexp instead of String, with i option that indicates that this regexp is case insensitive:

def add_more_ruby(string)
  string.gsub(/bad/i, 'good')
end

note that it will substitute not only 'bad' and 'BAD', but also, for example, 'bAd'. If you want to substitute only all-uppercase or all-lowercase, you can do:

string.gsub(/bad|BAD/, 'good')

Upvotes: 58

Related Questions