How to Capitalize String in Ruby

Stewart Nguyen Feb 02, 2024
  1. Use string.capitalize to Capitalize First String Character in Ruby
  2. Use string.upcase to Capitalize a String Character in Ruby
  3. Use the string.gsub Method With a Block to Capitalize a String Character in Ruby
  4. Use the string.titleize Method With a String Class to Capitalize a String Character in Ruby
  5. Conclusion
How to Capitalize String in Ruby

This tutorial provides a guide on how to capitalize a string in the Ruby language. It covers various methods to achieve this, catering to different scenarios and preferences.

Use string.capitalize to Capitalize First String Character in Ruby

In Ruby, the capitalize method is used to capitalize the first character of a string. When applied to a string, it returns a new string with the first character in uppercase, and the rest of the characters are converted to lowercase.

Code:

print 'capiTal'.capitalize

Output:

Capital

In this code, we use the capitalize method on the string 'capiTal'. The capitalize method returns a copy of the given string with the first character capitalized, while the rest of the characters are converted to lowercase.

In our example, the initial string is 'capiTal', and when we apply the capitalize method, the output is 'Capital'. This method is useful when you want to ensure that the first letter of a string is in uppercase, leaving the rest of the string in lowercase.

Use string.upcase to Capitalize a String Character in Ruby

In case the Ruby version does not support the string.capitalize method. We may need to write our function by making use of string.upcase and string.downcase methods.

The string.upcase method in Ruby is used to transform all the characters in a string to uppercase. When applied to a string, it returns a new string where every alphabetical character in the original string is converted to its uppercase equivalent.

On the other hand, the string.downcase method is used to convert all the characters in a string to lowercase. Similar to upcase, every alphabetical character in the string is transformed to its lowercase equivalent, while non-alphabetical characters remain unchanged.

Both methods return a new string with the modified case, leaving the original string unchanged. By using these two methods, we can capitalize a string character in Ruby.

Code:

def my_capitalize(string)
  return '' if string.nil? || string.empty?

  string.downcase!
  string[0] = string[0].upcase
  string
end

print my_capitalize('capiTal')

Output:

Capital

In this code, we define a custom method called my_capitalize that takes a string as a parameter. Initially, we check if the input string is either nil or empty, and if this condition is met, we return an empty string.

If the string is not nil or empty, we proceed to modify it. We use the downcase! method to convert the entire string to lowercase, ensuring consistent handling.

Then, we capitalize the first character of the string by assigning the result of string[0].upcase to the first character position. Finally, we return the modified string.

When we call this method with the argument 'capiTal' and print the result to the console, we get the output 'Capital'. This outcome reflects the string where the first letter 'c' is capitalized, and the subsequent letters 'apiTal' are in lowercase.

Use the string.gsub Method With a Block to Capitalize a String Character in Ruby

The string.gsub method in Ruby is used for global substitution in a string. The acronym gsub stands for “global substitution”.

This method takes two arguments: the first argument is the pattern to search for in the string, and the second argument is the replacement string.

When the gsub method is applied to a string, it globally replaces all occurrences of the specified pattern with the replacement string. The original string remains unchanged, and a new string with the substitutions is returned.

This method is particularly useful when you want to replace multiple occurrences of a specific substring within a string.

We can use the string.gsub with a block to capitalize each character for each match found in the string using the provided block.

Code:

string = 'capitalize string'
result = string.gsub(/\w+/, &:capitalize)
puts result

Output:

Capitalize String

In this code, we use the gsub method, which allows us to replace each word in the string based on a specified pattern. In this case, we use the regular expression \w+ to match each word in the string.

The &:capitalize syntax is a concise way to apply the capitalize method to each matched word within the block. As a result, every word in the original string is capitalized, considering the first letter of each word.

When we print the result to the console using puts, we obtain the output 'Capitalize String'. This reflects the transformation where each word in the original string is capitalized, demonstrating the effective use of the gsub method with a block for string manipulation.

Use the string.titleize Method With a String Class to Capitalize a String Character in Ruby

The titleize method is used to capitalize the first letter of each word in a string. Note that the titleize method is not a built-in Ruby method but can be added to the String class using a custom method.

Code:

class String
  def titleize
    split.map(&:capitalize).join(' ')
  end
end

string = 'capitalize string'
print string.titleize

Output:

Capitalize String

In this code, we define a custom method called titleize within the String class. This method takes a string, splits it into individual words using the split method, capitalizes each word using map(&:capitalize), and then joins the modified words back into a single string with spaces using join(' ').

When we create a string 'capitalize string' and call the titleize method on it using print, the output is 'Capitalize String'. The result showcases the application of the titleize method, which effectively capitalizes the first letter of each word in the original string, providing title-style formatting.

Conclusion

This article explored various methods in Ruby to capitalize strings, ranging from the straightforward capitalize and upcase methods to more customized approaches using gsub with a block and the creation of a titleize method. Each method provides a distinct way to achieve string capitalization, catering to different needs within Ruby programming.

Whether working with built-in functions or implementing custom solutions, Ruby offers versatility in string manipulation for developers.

Related Article - Ruby String