1

Given string "Lorem IPSUM dolor Sit amet". Capital letters in "Lorem" and "Sit" should be kept, uppercased ones like "IPSUM" should be converted to "Ipsum"

How to make "Lorem Ipsum dolor Sit amet" from given string using gsub? NOT working example: s.gsub(/[[:upper:]]/){$&.downcase}

1 Answer 1

1

You may use capitalize with /\b[[:upper:]]{2,}\b/ regex:

s.gsub(/\b[[:upper:]]{2,}\b/){$&.capitalize}
# => Lorem Ipsum dolor Sit amet

See the online Ruby demo.

Note that the \b[[:upper:]]{2,}\b pattern will match whole words (as \b are word boundaries) that only consist of 2 or more uppercase letters (there seems no need to match words like I that are already OK).

1
  • BTW, it is also possible to use \b[[:upper:]]{2,}\b to match words with 2 or more uppercase letters since I is already OK. I updated the answer. Mar 22, 2017 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.