In Ruby, we can capitalize the first letter of every word in a string easily with the help of the split and map methods, and the capitalize method. Let’s see the code for this first, and then go over what is happening.

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(" ")
print cap_string

#Output:
This Is A String With Some Words

We can put this code in a method that we will call capitalizeEachWord so that we can reuse this code whenever we want to capitalize all the words of a string.

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

And now let’s see our method in action with a simple example.

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"

print capitalizeEachWord(some_string)

#Output:
This Is A String With Some Words

When using string variables in Ruby, we can easily perform string manipulation to change the value of the string objects. One such manipulation is to capitalize the first letter of every word in a string. We can easily capitalize the first letter of every word using Ruby.

In our method 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.

Below is our method again called capitalizeEachWord which will capitalize the first letter of each word in a string object.

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"

print 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 each word.

Categorized in:

Ruby,

Last Update: March 1, 2024