How to convert a string to uppercase in Ruby

Overview

Converting a string to uppercase can be achieved using the upcase method. It converts the characters in a string to its corresponding uppercase.

It returns the uppercase of characters in a string. If nothing gets changed, nil is returned.

Syntax

str.upcase

Parameters

str: This is the string whose characters we want to convert to uppercase.

Return value

Characters in string str are returned as uppercase characters.

Code example

# create some strings
str1 = "educative"
str2 = "IS"
str3 = "greAT"
# convert to uppercase
a = str1.upcase
b = str2.upcase
c = str3.upcase
puts a
puts b
puts c

Explanation

Here is a line-by-line explanation of the above code:

  • Lines 2-4: We create some string variables, str1, str2 and str3, and initialize them with some values.

  • Lines 7-9: We convert characters in the strings to uppercase characters using the upcase method.

  • Lines 11-13: We print the results to the console.

As we can see in the output, all the characters in the strings are converted to uppercase characters. The only string that does not change is string str2.

Free Resources