Ruby How to Convert String to Lowercase Easily
In Ruby, you can convert a string to lowercase by using the
downcase method like this: string.downcase.Examples
Input"HELLO"
Output"hello"
Input"Ruby Is Fun"
Output"ruby is fun"
Input"123!@#"
Output"123!@#"
How to Think About It
To convert a string to lowercase, think about changing every uppercase letter to its lowercase form while leaving other characters unchanged. Ruby provides a built-in method called
downcase that does this easily for the whole string.Algorithm
1
Get the input string.2
Use the built-in method to convert all uppercase letters to lowercase.3
Return or print the converted lowercase string.Code
ruby
input = "Hello World!"
lowercase = input.downcase
puts lowercaseOutput
hello world!
Dry Run
Let's trace the string "Hello World!" through the code
1
Input string
input = "Hello World!"
2
Convert to lowercase
lowercase = input.downcase # "hello world!"
3
Print result
puts lowercase # outputs "hello world!"
| Step | String Value |
|---|---|
| Initial | Hello World! |
| After downcase | hello world! |
Why This Works
Step 1: Using downcase method
The downcase method converts all uppercase letters in the string to lowercase.
Step 2: Non-letter characters unchanged
Characters like spaces, numbers, and symbols remain the same because they have no lowercase form.
Alternative Approaches
Using tr method
ruby
input = "Hello World!" lowercase = input.tr('A-Z', 'a-z') puts lowercase
This replaces uppercase letters with lowercase manually but is less readable and less flexible than downcase.
Complexity: O(n) time, O(n) space
Time Complexity
The method processes each character once, so time grows linearly with string length.
Space Complexity
A new string is created for the lowercase result, so space also grows linearly.
Which Approach is Fastest?
The built-in downcase method is optimized and preferred over manual replacements like tr.
| Approach | Time | Space | Best For |
|---|---|---|---|
| downcase | O(n) | O(n) | Simple, readable lowercase conversion |
| tr('A-Z', 'a-z') | O(n) | O(n) | Manual replacement, less readable |
Use
downcase for a simple and clear way to convert strings to lowercase in Ruby.Forgetting to call
downcase on the string and trying to assign it without parentheses or missing the method call.