Ruby String Methods (Ultimate Guide)

A string is a sequence of characters.

Strings are objects so they have a lot of methods you can use to do things with them.

In this article…

You’ll discover the most useful Ruby string methods with examples!

How to Get The String Length

Easy:

"ruby".size
# 4

You can also use length, instead of size, they do the same thing.

How to Check If A String Is Empty

We define an empty string as a string of zero length.

You can check like this:

"".size == 0
# true

Or even better, use the empty? method.

Example:

"".empty?
# true

A blank string is a string that has either zero-length, or is composed ONLY of white space characters.

What is String Interpolation?

String interpolation allows you to combine strings together:

name = "Jesus"

puts "Hello #{name}"

What some people don’t know is that you can have actual code inside the interpolation.

Here’s an example:

puts "The total is #{1+1}"

# "the total is 2"

Ruby calls the to_s method on the string interpolation block, this tells the object to convert itself into a string.

How to Extract a Substring

A substring is a smaller part of a string, it’s useful if you only want that specific part, like the beginning, middle, or end.

How do you get a substring in Ruby?

One way is to use a starting index & a number of characters, inside square brackets, separated by commas.

Like this:

string = "abc123"

string[0,3]
# "abc"

string[3,3]
# "123"

The first number is the starting index.

The second number is how many characters you want.

You can also use a range if you want to do something like “get all the characters but the last one”.

Example:

string = "abc123"

string[0..-2]
# "abc12"

Now, the first index is still the starting index, but the second index is the ending index (inclusive). This -2 is the second to last character, and -1 is the end of the string.

If you want to remove or replace the substring.

You can do this:

string[0..2] = ""

p string
# "123"

Very nice!

How to Find Out If a String Contains Another String

What’s the easiest way to find if a string is included in another string?

The include? method:

string = "Today is Saturday"

string.include?("Saturday")
# true

You can also use the index method:

string = "Today is Sunday"

string.index("day")
# 2

This method looks for partial words & instead of returning true or false it will give you the index where the start of this string is found.

In this example, index is finding the “day” in “Today”.

If you want to find patterns (like all the words containing the word “day”) you are looking for regular expressions.

How to Pad a Ruby String

One way to pad a string is to use the rjust method with two arguments:

binary_string = "1101"
binary_string.rjust(8, "0")

# "00001101"

If you want to pad to the right you can use ljust:

binary_string = "1111"
binary_string.ljust(8, "0")

# "11110000"

Compare Strings Ignoring Case

Because string comparison is case-sensitive you want to make sure the two strings you’re comparing are in the same case.

The common way to do that is to make both sides of the equation downcase or upcase.

Example:

lang1 = "ruby"
lang2 = "Ruby"

lang1.upcase == lang2.upcase

There is also a casecmp? method that does a case-insensitive comparison, but it’s rarely used.

Stick with the example above.

How to Trim a String & Remove White Space

When reading data from a file or a website you may find yourself with extra white space in your string.

You can remove that extra space with the strip method:

extra_space = "   test    "
extra_space.strip

# "test"

If you only want to remove the white space from one of the sides (left / right) you can use the lstrip & rstrip methods instead.

String Prefix & Suffix

You can use the start_with? method to check if a string starts with a specific prefix.

Here’s an example:

string = "ruby programming"

string.start_with? "ruby"
# true

There’s also an end_with? method:

string = "ruby programming"

string.end_with? "programming"
# true

In addition, Ruby 2.5 introduced the delete_prefix & delete_suffix methods, which may be useful to you.

Here’s an example:

string = "bacon is expensive"

string.delete_suffix(" is expensive")

# "bacon"

Convert a String to An Array of Characters

Taking a string & breaking it down into an array of characters is easy with the split method.

Example:

string = "a b c d"

string.split
# ["a", "b", "c", "d"]

By default split will use a space as the separator character, but you can pass an argument into this method to specify a different separator.

Here’s how you can split a list of comma-separated values (CSV):

csv = "a,b,c,d"

string.split(",")
# ["a", "b", "c", "d"]

But if you are working with CSV data specifically you may want to consider using the CSV class from the standard library. This class can do things like reading column headers, so it makes things easier for you.

Convert an Array to a String

If you would like to take an array of strings & join these strings into a big string you can use the join method.

Example:

arr = ['a', 'b', 'c']

arr.join
# "abc"

It’s also possible to pass an argument to join, this argument is the character separator.

Example:

arr = ['a', 'b', 'c']

arr.join("-")
# "a-b-c"

Convert a String Into An Integer

If you want to convert a string like "49" into the Integer 49 you can use the to_i method.

Example:

"49".to_i

Notice that if you try this with a string that contains no numbers then you will get 0.

Example:

"a".to_i
# 0

Check If A String Is A Number

Would you like to know if a string is made of only whole numbers?

You can do this:

"123".match?(/\A-?\d+\Z/)
# true

"123bb".match?(/\A-?\d+\Z/)
# false

Note: The match? method was introduced in Ruby 2.4, you can use match (without the question mark) on older versions.

This code uses a regular expression, let me translate it for you:

“From the start of the string (\A) check if there is an optional dash (-?, for negative numbers), then make sure there are some numbers in there (\d+) & nothing else until the end of the string (\Z).”

How to Append Characters

You can build up a big string from smaller strings by appending characters to an existing string. We also call this string concatenation.

Here’s how to do that using the << method:

string = ""

string << "hello"
string << " "
string << "there"

# "hello there"

Don’t use += for string concatenation because that will create a new string every time, which is not good for performance!

Iterate Over Characters Of a String in Ruby

Sometimes it’s useful to work with the individual characters of a string.

One way to do that is to use the each_char method:

"rubyguides".each_char { |ch| puts ch }

You can also use the chars method to convert the string into an array of characters. Then you can use each on this array to iterate.

Example:

array_of_characters = "rubyguides".chars
# ["r", "u", "b", "y", "g", "u", "i", "d", "e", "s"]

How to Convert a String to Upper or Lowercase in Ruby

If you would like to convert a string to all upper case you can use the upcase method.

Example:

"abcd".upcase
# "ABCD"

And if you want to convert to lower case you can use the downcase method.

Example:

"ABCD".downcase
# "abcd"

How to Create Multiline Strings

You can create multi-line strings in two different ways.

One is by using heredocs:

b = <<-STRING
aaa
bbb
ccc
STRING

And another is by using %Q:

a = %Q(aaa
bbb
ccc
)

How to Replace Text Inside a String Using The Gsub Method

If you want to replace text inside a string use the gsub method.

Let’s replace the word “dogs” with “cats”:

string = "We have many dogs"

string.gsub("dogs", "cats")

# "We have many cats"

If you want to remove the string use an empty string as the 2nd argument.

Example:

string = "abccc"

string.gsub("c", "")

# "ab"

Now:

The gsub method returns a new string.

If you want to apply the changes to the original string you can use the gsub! method.

The gsub method also takes regular expressions as an argument so you can replace patterns instead of exact words.

Here’s an example:

string = "We have 3 cats"

string.gsub(/\d+/, "5")

# "We have 5 cats"

This replaces all the numbers (\d+) in the string with the number 5.

One more way to use this method, with a block:

title = "the lord of the rings"

title.gsub(/\w+/) { |word| word.capitalize }
# "The Lord Of The Rings"

What about gsub vs sub?

Well, sub is the same as gsub, but it will only replace the first match.

Gsub replaces ALL matches.

How to Remove the Last Character From a String

If you are asking the user for some input (using the Kernel#gets method) then you will have a newline character (\n) at the end of your string, this prevents you from comparing the string directly.

Example:

puts "What's your name?"
name = gets

# type something...

The best way to remove that extra newline character (\n) is to use the chomp method.

Example:

name = gets.chomp

Since Ruby 2.3 the chomp method takes an optional argument that allows you to remove the characters you want to remove.

Example:

"abcd?".chomp("?")
# "abcd"

And if the character is not there it will return the original string.

How to Change String Encodings

Strings are stored as a sequence of bytes, they are turned into the characters that you can see based on their encoding.

For example, the number 65 in the ASCII encoding represents the letter “A”.

But there are also more complex encodings, like UTF-8, which allow you to represent characters from different languages (Chinese, etc.) & even emojis.

To find out the current encoding for a string you can use the encoding method.

"abc".encoding

# Encoding:UTF-8

When reading a file from disk or downloading some data from a website you may run into encoding problems.

You can often fix that problem by enforcing the encoding.

Like this:

"abc".force_encoding("UTF-8")

Counting Characters

You can count how many times a character appears in a string by using the count method.

Example:

str = "aaab"

str.count("a")
# 3

str.count("b")
# 1

Summary

You learned about many string methods, like join & split to break down strings into arrays, gsub to replace text inside strings & strip to trim out extra white space.

Since you may want to reference this page later make sure to bookmark it & share it with all your Ruby friends 🙂

Thanks for reading!

17 thoughts on “Ruby String Methods (Ultimate Guide)”

    • Thanks for reading Tom! Let me know if there is any specific topic you would like me to cover 🙂

  1. In your post, you mentioned the method ‘casecmp?’ as a way to do case-insensitive string comparisons. However, you also recommended not to use it and instead prefer comparing up/downcased strings.

    What is the downside to using ‘casecmp?’?

    • Abdullah, I don’t think there is any real downside, it just doesn’t feel like something you would use in Ruby.

      • I found your page because I was trying to figure out how to switch from downcase with the spaceship operator to casecmp, because rubocop blows up demanding casecmp, and we use rubocop for styling. casecmp is much faster when benchmarking, which is why I suspect the style guide is directing us that way. Meanwhile, I’m still not getting casecmp to work properly. I may need to disable rubocop there, but that’s not my first choice.

        • It looks like this is defined as a performance rule in Rubocop.

          The example given is this:

          str.casecmp('ABC').zero?

          I don’t like this at all, so I would avoid that unless you really need the performance boost.

        • I ended up getting it to work just fine, and my company uses rubocop to process our pull requests, as did the last place it works. I suspect we’ll start seeing more of it. In any case, I’m glad to see your post! Every piece of info helps out here!

  2. Hi there! Great article, I am missing “<<~ curly doc”, maybe you can add it 🙂

    Keep up the good work and thank you so much for this article!

  3. In your “How to Remove the Last Character From a String” topic the very lasg sentence says “And if the character is not there it will return the original array” I believe you meant string not array. Love the article though it didn’t occur to me that String#+ creates a new string object every time and String#<< does proper string concatenation to the original string! Cheers.

Comments are closed.