Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swap
ruby
string
communitycreator

How to swap cases in a string in Ruby?

okwudili onyejiaku

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
Swap cases of characters of a String in Ruby

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.

RELATED TAGS

swap
ruby
string
communitycreator
RELATED COURSES

View all Courses

Keep Exploring