
String to Uppercase in Ruby
In this article, you will discover how to handle capital letters in a string in Ruby.
Capitalize the first letter with capitalize
A string in Ruby is a simple text between ‘ ‘ or between ” “. It fits on one line. As an example:
"Hello world"
To modify this string and put the first letter in uppercase, there is the capitalize function:
puts "hello world".capitalize
// output: "Hello world"
Whatever the starting state of the string, the ending state will always be the same:
puts "HELLO WORLD".capitalize
// output: "Hello world"
puts "hello World".capitalize
// output: "Hello world"
Attention, if there is a number at the beginning of the string, this gives:
puts "2 hello world".capitalize
// output: "2 hello world"
puts "2 HELLO WORLD".capitalize
// output: "2 hello world"
Capitalize the entire string with upcase
The upcase function will help you to modify the string and put all the letters in uppercase:
puts "hello world".upcase
// output: "HELLO WORLD"
Whatever the starting state of the string, the ending state will always be the same:
puts "Hello World".upcase
// output: "HELLO WORLD"
In addition, I invite you to read my article on how to lowercase a string in Ruby.