How to swap cases in a string in Ruby?
Overview
We can change lowercase characters in a string in Ruby to uppercase characters and vice versa using the swapcase method.
Syntax
str.swapcase
Parameters
str: This is the string whose characters’ cases we want to swap.
Code example
# creates some stringsstr1 = "edpresso"str2 = "IS"str3 = "awESoMe"# swap casesputs str1.swapcaseputs str2.swapcaseputs str3.swapcase
Explanation
- Lines 2 to 4: Several strings
str1,str2, andstr3are created and initialized with some values. - lines 7 to 9: The
swapcasemethod is called on the strings we create. We then print the result.