How to Use Strings in Ruby

Jul 29, 2020 - 7 min read
How to Use Strings in Ruby

I remember when I first heard about strings (I wasn't using Ruby at the time so it wasn't a Ruby string). I wanted to create a command line application that would ask the user for his name and age. I can't remember what the application was about, but I do remember that was the first time I've heard about strings.

In order to capture the user's name, I had to use a string variable. Because that's how computers call those things. Fun times :)

What is a Ruby string?

Different languages have different ways of handling strings, so it's worth mentioning what strings mean in Ruby.

A string in Ruby is an object (like most things in Ruby).

You can create a string with either String::new or as literal (i.e. with the double quotes ""). But you can also create string with the special %() syntax With the percent sign syntax, the delimiters can be any special character.

Lets see a few examples.

"this is a string""this is another string")
%(this is yet another string)
%/this is also a string/

String methods

Strings are objects, and so you can call methods on the string object. And there are a ton of methods you can use.

"a string".upcase # => "A STRING"
"|---|" * 3 # => "|---||---||---|"
"another string".length # => 14

Let's see a few cool tricks you can do with string methods in Ruby

How to convert a string to lower/upper case

"a string".upcase # => "A STRING"
"A STRING".downcase # => "a string"

How to generate a random string

Let's say you need an eight character long random string. Here's one way to do it.

(0...8).map { (65 + rand(61)).chr }.join

That line deserves some explanation.

First, we [create an array]({% post_url 2018-07-03-learn-how-to-use-ruby-arrays %}) with eight elements by using a range (i.e. (0...8)). Then, we change each one of those elements by mapping through the array. And as the value replacing the element, we generate a random character.

The character generation simply picks any number between 65 and 126 and calls chr on it to convert the int into its character representation.

How to check whether a string contains a substring

"a string".include?("str") # => true

You could also use the element reference, which returns the string given as an argument if it matched.

"a string"["str"] # => "str"

You could even use a regular expression. Let's say you want to see if the string ends with the characters ng.

"a string" =~ /ng$/ # => 6

And to check if the string starts with a substring.

"a string" =~ /^a\s+/ # => 0

Note that the returned value is the position where the match was found in the string.

String concatenation

String concatenation is as simple as adding two strings together. And you would get a completely new string.

"abc" + "bcd" # => "abcbcd"

You could also append one string to another.

"abc" << "bcd" # => "abcbcd"

Note thought that this is not a new string. By appending a string, you are changing the initial string, you can verify this if you want.

my_string = "abc"
my_string + "bcd" # => "abcbcd"
my_string # => "abc"

my_string << "bcd"
my_string # => "abcbcd"

Parsing a JSON string

JSON parsing is popular enough in the Ruby world so I thought it would be useful to include it here. Ruby provides a module out of the box for you to work with JSON.

require 'json'
string = %({"name": "John Doe"})
JSON.parse(string) # => {"name"=>"John Doe"}

Note that you can't use single quotes for either the keys or the values. So this will not work.

string = %({'name': 'John Doe'})
JSON.parse(string) # => JSON::ParseError

How to convert strings to symbols

While converting a regular string like "hello" into a symbol might be as easy as calling to_sym on it, when it comes to strings with spaces in them, using to_sym won't automatically convert your string into a snake case symbol. You need to do it yourself.

"First Last Name".to_sym # => :"First Last Name"
"First Last Name".gsub(/\s+/, "_").downcase.to_sym # => :first_last_name

How to read the contents of a file

Let's say you want to get the string representation of a file. Text or binary file, doesn't matter.

You can use the File module to read the contents into a string variable. Like so.

content ="my_file.rb")

How to remove substrings from strings

You would expect to find a delete method or remove to do that. I know I did.

But the fact is there's no such method. The method you would use for removing a substring from a string by using the sub method.

my_string = "this is my message"
my_string.sub(" message", "") # => "this is my"

If you need to replace all the occurrences of the substring from the string, you can use gsub which stands for global.

my_string = "this is my message"
my_string.sub("i", "*") # => "th*s is my message"
my_string.gsub("i", "*") # => "th*s *s my message"

You should not that those methods are non-destructive, meaning they return a new string. If you want to change the string in place, you would have to use the bang version (!).

my_string = "this is my message"
my_string.object_id # => 70144341686300
my_string.sub("i", "*").object_id # => 70144341783940
my_string.gsub("i", "*").object_id # => 70144341847500

my_string.sub!("i", "*").object_id # => 70144341686300
my_string.gsub!("i", "*").object_id # => 70144341686300

Comparing strings regardless of case

Sometimes you just want to know if the contents of a string is equal with another string. So basically you don't care about any of the strings' case. That is called a case insensitive comparison. And in Ruby you can do it with the casecmp method.

"abcdef".casecmp("abcde")     #=> 1
"aBcDeF".casecmp("abcdef")    #=> 0
"abcdef".casecmp("abcdefg")   #=> -1
"abcdef".casecmp("ABCDEF")    #=> -1

There's also a case sensitive way to compare two strings.

"abcdef" <=> "abcde"     #=> 1
"abcdef" <=> "abcdef"    #=> 0
"abcdef" <=> "abcdefg"   #=> -1
"abcdef" <=> "ABCDEF"    #=> 1

How to remove the extra whitespace from a string

Have you ever dealt with user input. I bet you have. But getting rid of extra spaces is not only useful for user input. So let's see how it's done in Ruby.

" abc ".strip # => "abc"
" abc ".strip! # => "abc"

As you can see, there are two versions of the strip method. The first, and non-destructive` version returns a new string object, while the second one, changes the existing object.

As a side note, strip only works with ASCII whitespace.

" abc\xc2\xa0".strip
" abc\xc2\xa0".gsub(/[[:space:]]+/, "" # => "abc"

(thank you sshaw_ for pointing this out)

How to split a delimited string and convert it to an array

If you want to learn more about arrays, you can check out the article on working with arrays in Ruby.

If you have a string that uses some kind of separator, you can use it to create an array. Like so.

"a b c".split(" ") # => ["a", "b", "c"]

How to convert a date into a string

I always forget how to convert a date or time object into the string that I want. There are too many options to strftime but I do what to share an awesome resource you can use to do it. It gives you the right format and all you need to do is paste it in your code.

So let's say I want to take today's date and convert it into a string like: <full day name>, <month in three letters> <year, two letters>. So I would go to For a Good Strftime, I would choose the format I want, and then copy paste the format string in my code like so.

require 'date'"%A, %b %d") # => "Monday, Jan 01"

And there you go. You now know how to use a Ruby string, and also perform a few nice tricks with it.

12 Project Ideas
Cezar Halmagean
Software development consultant with over a decade of experience in helping growing companies scale large Ruby on Rails applications. Has written about the process of building Ruby on Rails applications in RubyWeekly, SemaphoreCI, and Foundr.