0
0
RubyHow-ToBeginner · 2 min read

Ruby How to Convert String to Uppercase Easily

In Ruby, you can convert a string to uppercase by calling the upcase method on the string, like "hello".upcase which returns "HELLO".
📋

Examples

Input"hello"
Output"HELLO"
Input"Ruby Programming"
Output"RUBY PROGRAMMING"
Input"123abc!"
Output"123ABC!"
🧠

How to Think About It

To convert a string to uppercase, think of changing every lowercase letter to its uppercase version while leaving other characters unchanged. Ruby provides a simple method called upcase that does this for you automatically.
📐

Algorithm

1
Take the input string.
2
For each character in the string, check if it is a lowercase letter.
3
If it is lowercase, convert it to uppercase.
4
Leave all other characters as they are.
5
Return the new string with all letters in uppercase.
💻

Code

ruby
str = "hello world"
puts str.upcase
Output
HELLO WORLD
🔍

Dry Run

Let's trace "hello" through the code

1

Input string

"hello"

2

Call upcase method

"hello".upcase

3

Output string

"HELLO"

OriginalAfter upcase
helloHELLO
💡

Why This Works

Step 1: What upcase does

The upcase method converts all lowercase letters in the string to uppercase letters.

Step 2: Non-letter characters

Characters that are not letters, like numbers or symbols, remain unchanged by upcase.

Step 3: Returns new string

upcase returns a new string with uppercase letters and does not modify the original string unless you use upcase!.

🔄

Alternative Approaches

upcase!
ruby
str = "hello"
str.upcase!
puts str
This method changes the original string in place instead of returning a new one.
tr method
ruby
str = "hello"
puts str.tr('a-z', 'A-Z')
This replaces lowercase letters with uppercase manually but is less readable than upcase.

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 to hold the uppercase result, so space also grows linearly.

Which Approach is Fastest?

upcase is optimized and clear; alternatives like tr are less readable and not faster.

ApproachTimeSpaceBest For
upcaseO(n)O(n)Simple and clear uppercase conversion
upcase!O(n)O(1)In-place modification to save memory
tr('a-z', 'A-Z')O(n)O(n)Manual replacement, less readable
💡
Use upcase to quickly convert any string to uppercase in Ruby.
⚠️
Forgetting that upcase returns a new string and does not change the original string unless you use upcase!.