What is the swapcase method in Ruby?

The swapcase method in Ruby creates a copy of the original string. It converts uppercase characters of the original string to lowercase and lowercase characters to uppercase.

Uppercase characters consist of A-Z.

Lowercase characters consist of a-z.

The illustration below shows how the swapcase method works in Ruby:

How does swapcase work in Ruby

Syntax

The swapcase method works on a string. We use the . operator to link the string with the method. Here is an example:

"string".swapcase

Return value

The swapcase method in Ruby returns a copy of the original string with cases swapped.

Example

The code snippet below shows how we can use the swapcase method in Ruby:

puts "String".swapcase
puts "string".swapcase
puts "STRING".swapcase
puts "StRinG".swapcase

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved