Working With Strings In Ruby — All the Important Methods You Need to Know

Working with strings is one of the most common things you’ll do when working with Ruby or Ruby on Rails. Luckily, Ruby has all sorts of great built-in methods that help us work with strings.

I put together this guide so you know what methods are available to you when working with strings in Ruby.

I’d like to shoutout to this article which inspired me to write this guide.

String Methods in Ruby

How to get a string’s length in Ruby.

This is one of the most common things you’ll do when working with strings. You can use the size or length methods to get the number of characters of a string in Ruby.

How to check if a string is empty in Ruby.

There are two ways to determine if a string is empty in Ruby. You can compare the size or length to 0 or you can use the empty method.

How to extract a substring in Ruby.

You can extract a substring from a string in Ruby by using a starting index number and the number of characters you want to get.

How to find out if a string contains another string in Ruby.

With this method, you can see if a string contains a substring.

HINT: There are many methods in Ruby that end with a question mark (?) that return a boolean.

How to convert the case of a string in Ruby.

Ruby has downcase and upcase methods you can use to easily change the case of a string.

How to compare strings in Ruby.

You can compare strings using “==”, but strings are case-sensitive. Because of this, it’s common practice to call downcase or upcase on both strings to convert them into the same case before comparing them.

How to trim a string and remove whitespace in Ruby.

Sometimes you want to get rid of whitespace at the beginning or end of a string. Use the strip method to take care of it.

How to convert a string into an array in Ruby.

You can use the split method to convert a string into an array in Ruby You can choose to pass it an argument if you want to, but you don’t have to.

How to concat strings in Ruby.

Just use the shovel operator (<<) to concat strings in Ruby.

How to convert a string into an integer in Ruby.

The to_i method is the method you’re looking for here.

If you call this method on a string, you get 0.

How to check if a string is an integer in Ruby.

You can convert the integer to a string and then back into an integer and compare it to the original. This has limited uses and won’t catch all edge cases.

A more robust way is to use regex to check if the input is a number.

How to make a multiple-line string in Ruby.

Use %Q to create a multi-line string in ruby.

How to check if a string starts with another string in Ruby.

The starts_with? method is the method to use here.

How to check if a string ends with another string in Ruby.

And we can use the ends_with? method for this one.

This guide will most likely evolve once I can think of some useful string methods in Ruby.

Marketing and language expert