We can use Ruby to capitalize the first letter of a string by using the Ruby capitalize method.

some_string = "how are you?"
some_string.capitalize

Let’s look at a simple example below.


Let’s say we have a string and we simply want to capitalize the first letter in that string. To do this we can use our code from above.

some_string = "how are you?"
some_string = some_string.capitalize

puts some_string

#Output
How are you?

We can also use Ruby to capitalize every word of a string. Let’s take a look at that below.

Using Ruby to Capitalize Every Word in a String

To capitalize every word in a string, we will need to make use of the Ruby split, join, and map methods. We have a whole post on how to do this, but we will go over it again here.

some_string = "this is a string with some words"
words_array = some_string.split(" ")
cap_array = words_array.map { |word| word.capitalize }
cap_string = cap_array.join(" ")

puts cap_string

#Output:
This Is A String With Some Words

In our code above, we first can use the split method to split the string by spaces to get an array of the words of the string object (convert the string to an array). We store this array in a variable called words_array. Then, we can loop over each word using the map method and call the capitalize method on each word in our array.

Finally, at the end, we can convert the array back to a string using the join method.

We can put this code in a method so that we can reuse it whenever we want.


def capitalizeEachWord(str)
  words_array = str.split(" ")
  cap_array = words_array.map { |word| word.capitalize }
  cap_string = cap_array.join(" ")
  return cap_string
end

some_string = "this is a string with some words"

puts capitalizeEachWord(some_string)

#Output:
This Is A String With Some Words

Hopefully this article has been useful for you to learn how to use Ruby to capitalize the first letter of a string.

Categorized in:

Ruby,

Last Update: March 1, 2024