27

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
sawa
  • 165,429
  • 45
  • 277
  • 381
Stacca
  • 791
  • 2
  • 8
  • 19
  • 1
    If you are not sure of a behavior of a method, it is better not to make a wild guess in describing it. Here, your mentioning of `capitalize` is irrelevant to what you actually wanted to do, and it is making your question very hard to understand. Instead, write what you want to do in ordinary words. – sawa Mar 12 '15 at 12:27
  • 2
    Do you expect `Bad` to be replaced with `Good` or with `good`? – Stefan Mar 12 '15 at 13:21

2 Answers2

54

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')
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
0

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'.

Dan
  • 778
  • 11
  • 18