What is the difference between downcase and downcase! in Ruby?

Overview

The downcase and downcase! methods are used to convert a string to lowercase.

The difference between the downcase! and downcase methods is that downcase does not modify the string that calls it, but downcase! permanently changes a string to lowercase. Therefore, if we want to permanently change a string to lowercase, we use the downcase! method.

Syntax

# no modification
str.downcase

# modification
str.downcase!

Parameters

  • str: The string that calls the method.

Return value

The return value for both strings is a lowercase version of str.

Example

# create some strings
str1 = "EDPRESSO"
str2 = "IS"
str3 = "AweSOME!"
str4 = "AND"
str5 = "EDUcative!"
# downcase the
# strings temporarily
puts str1.downcase
puts str1
puts str2.downcase
puts str2
puts str3.downcase
puts str3
# downcase the
# strings permanently
puts str4.downcase!
puts str4
puts str5.downcase!
puts str5

Explanation

  • Lines 2 to 6: We create string variables and initialize them.
  • Lines 10 to 15: We call the downcase method on some of the strings and print the values of the strings and their downcase.
  • Lines 19 to 22: We call the downcase! method on the remaining strings and print the values of the strings and their downcase!.

When we run the code, only the strings that call the downcase! method are permanently changed to lowercase, and the rest that call the downcase method are not changed.

Free Resources