Adding a Function to the String Class

Published by bangyen in

One of the fun parts of Ruby is that you can extend all the standard types by extending their class. In this challenge, you need to give Ruby Strings a swap_case() function, which will return a new string with all upper case characters swapped for lower case characters, and vice versa. Any non-alphabetic characters should be kept as they are.

Examples

"Hello".swap_case ➞ "hELLO"

"2 4 6 8 WHO DO WE APPRECIATE?".swap_case ➞ "2 4 6 8 who do we appreciate?"

"aBcD".swap_case.swap_case ➞ "aBcD"

Notes

  • swap_case() should not alter the original string.
  • Although you can add new functions to the standard data types, it's not generally a good idea in large projects!
  • Do not use swapcase().
Watch a quick demo on how Edabit works.