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 strings
str1 = "edpresso"
str2 = "IS"
str3 = "awESoMe"
# swap cases
puts str1.swapcase
puts str2.swapcase
puts str3.swapcase

Explanation

  • Lines 2 to 4: Several strings str1, str2, and str3 are created and initialized with some values.
  • lines 7 to 9: The swapcase method is called on the strings we create. We then print the result.