Ruby Cases

Khalidh Sd
2 min readMay 12, 2023

--

In Ruby, there are several methods that you can use to manipulate the case of a string. Here are some of the most commonly used methods:

upcase: This method returns a new string with all letters converted to uppercase.

str = "hello, world"
puts str.upcase # Output: HELLO, WORLD

downcase: This method returns a new string with all letters converted to lowercase.

str = "HELLO, WORLD"
puts str.downcase # Output: hello, world

capitalize: This method returns a new string with the first letter of the string converted to uppercase and the rest of the string converted to lowercase.

str = "hello, world"
puts str.capitalize # Output: Hello, world

swapcase: This method returns a new string with uppercase letters converted to lowercase and lowercase letters converted to uppercase.

str = "HeLLo, WoRLd"
puts str.swapcase # Output: hEllO, wOrlD

titleize: This method converts the first letter of each word in a string to uppercase.

str = "hello, world"
puts str.titleize # Output: Hello, World

Camel case: camelcase method converts a string to camel case, where the first word is lowercase and subsequent words start with uppercase letters.

string = "hello world"
string.camelcase #=> "helloWorld"

Snake case: snakecase method converts a string to snake case, where words are separated by underscores and all letters are lowercase.

string = "Hello World"
string.snakecase #=> "hello_world"

Kebab case: kebabcase method converts a string to kebab case, where words are separated by hyphens and all letters are lowercase.

string = "Hello World"
string.kebabcase #=> "hello-world"

Note 1: that some of these methods are not built into Ruby by default and may require the installation of additional libraries.

Note 2: that the above methods all return a new string and do not modify the original string. If you want to modify the original string, you can use the bang (!) version of these methods, for example, str.upcase! will modify str to all uppercase letters.

--

--