How to Use the Ruby downcase Method

09/24/2021

Contents

In this article, you will learn how to use the Ruby downcase method.

Using the downcase method

The downcase method is a built-in method in the Ruby programming language. It is used to convert all the uppercase characters in a string to lowercase characters.

The downcase method can be used in several ways in Ruby. Here are some examples:

Basic usage

The simplest way to use the downcase method is to call it on a string object. Here is an example:

string = "HELLO WORLD"
puts string.downcase
# Output: hello world

In this example, the downcase method is called on the string object string, which contains the text “HELLO WORLD”. The method returns a new string with all the uppercase characters converted to lowercase.

Chaining method

The downcase method can be chained with other string methods to manipulate the text in various ways. For example:

string = "  HELLO   WORLD  "
puts string.downcase.strip
# Output: hello   world

In this example, the downcase method is chained with the strip method, which removes leading and trailing whitespace from the string. The resulting string is all lowercase with extra whitespace removed.

Assigning to a variable

The downcase method can be assigned to a variable, which can be useful when you need to manipulate the lowercase string further. For example:

string = "HELLO WORLD"
lowercase_string = string.downcase
puts lowercase_string.reverse
# Output: dlrow olleh

In this example, the downcase method is called on the string object string, and the resulting lowercase string is assigned to the variable lowercase_string. The reverse method is then called on lowercase_string to reverse the order of the characters.

Using with regular expressions

The downcase method can be used in combination with regular expressions to manipulate the text in more complex ways. For example:

string = "HELLO123WORLD"
puts string.downcase.gsub(/\d/, '*')
# Output: hello***world

In this example, the downcase method is called on the string object string, and the resulting lowercase string is passed to the gsub method. The regular expression /d matches all digits in the string, and the gsub method replaces each digit with an asterisk.