Share this post!

All posts by Jesus Castello

ruby string methods

Ruby String Methods (Ultimate Guide)

A string is just a sequence of characters.

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

In this article you will find the most useful Ruby string methods with examples!

How to Get The String Length


What is String Interpolation?

String interpolation allows you to combine strings together:

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

Probably not something you want to do often, but here’s an example:

How to Extract a Substring

If you only want part of a string, instead of the whole string, then you can use a range to extract that substring.

Like this:

The first number is the starting index & the second number is the number of characters you want.

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


In this code the first index is the starting index & the second index is the ending index (inclusive).

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:

You can also use the index method:

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:

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

Compare Strings Ignoring Case

Since string comparison is case-sensitive you want to make sure that both your strings are in the same case.

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


There is also a casecmp? method that does a case insensitive comparison, but it’s rarely used, stick with the method 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:

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:

There’s also an end_with? method:

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

Here’s an example:

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.


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):

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 do that using the join method.


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


Convert an String Into An Integer

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


Notice that if you try this with a string that contains no numbers then you will get 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:

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:

Don’t use += for this 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:

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.


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.


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


How to Create Multiline Strings

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

One is by using heredocs:

And another is by using %Q:

How to Replace Text Inside a String

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

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

Notice that gsub will return 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:

This will replace all the numbers in the string with the number 5.

There is one more way to use this method, with a block:

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.


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

It’s good to know that since Ruby 2.3 this method takes an optional argument that allows you to remove the characters you want to remove.


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.

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:


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 🙂

Ruby Loops

The Definitive Guide to Loops in Ruby

In this article you will learn many different ways to write a Ruby loop.

A loop lets you repeat some action a number of times.

You can also go over a list of things, like an array or a hash, and work with each individual element.

If you are a beginner I don’t want you to get overwhelmed by all the options. So stick with the each & times methods described here.

For my more advanced readers this will help you review & expand your toolbox of looping methods.

The Each Loop

This loop requires you to have a collection of items, like an array, a range or a hash to be able to use it.


This will print all the numbers inside the numbers array [1,3,5,7].

Notice how we have this syntax with the |n|.

In case you are not familiar with this, we call the whole thing after each a block { |n| puts n }.

A block is just a way to create a method without a name.

So what happens is that each, or any other method that takes a block, is able to use our name-less method.

And that’s how puts n is run multiple times.

If you want to use each with a hash you will need two parameters (one for the key & another for the value).


Give this a try 🙂

Each With Index

There are some cases where you want to use each but you need the index number.

You can use the each_with_index method:

The Times Loop

This is possibly the easiest loop you can come up with.

Look at this code:

This will print the word "hello" 10 times.

As you can see there isn’t much to it & it should be easy to remember.

But what if you want the number?

In the last example, with the each loop, we had access to this n so we could print it.

You can also do that with times.


This will print hello 0, hello 1, hello 2, etc.

Give it a try!

The key here is the little |i| thing, which by the way, can be anything. It doesn’t have to be an |i|. It could be |n| or |foo|, or |bacon|

It’s just a name!

If you are familiar with methods, this |n| is like a method parameter. In other words, it’s just a variable that becomes the current value for each iteration of our times loop.

Range Looping

You may have noticed that when using the times method it starts counting from 0.

This can be a bit inconvenient if you want to start with a different number.

You can use a range & the each method to have more control over the starting & ending numbers.


This will print all numbers from 1 to 10.

Ruby While Loop

The while loop is available in most programming languages so it’s always useful to know. It’s also the kind of loop that you can fall-back to when everything else fails.

And there are some situations when only a while loop would make sense. For example, if you don’t know how many times you need to loop in advance.

Here’s a code example:

This will print all the numbers from 0 to 9 (10 excluded).

Notice that there are some important components:

  • The n variable
  • The condition (n < 10)
  • The n += 1

All of these components are critical for this to work.

The variable n holds the value we are using for counting, the condition (n < 10) tells Ruby when to stop this loop (when the value of n is greater or equal to 10), and the n += 1 advances the counter to make progress.

Skipping Iterations

In all of these loop types you can skip iterations.

Let’s say that you are going over an array of numbers & you want to skip odd numbers.

You could do something like this:

The key here is the next keyword, which skips to the next loop iteration (the next number in this case).

A better way to do this is to use other methods like step & select.


Stopping Early

You can also break out of a loop early, before the condition is met, or before you go over all the elements of the collection.

The following example stops when it finds a number higher than 10:

The key here is the break keyword.

The Kernel#loop Method

The last kind of loop we are going to talk about is literally the loop method.

This method takes a block & it runs an infinite number of times.


You can stop a loop method in two ways:

  • Raising a StopIteration exception
  • Using the break keyword


You have learned many different ways to loop in Ruby! Including the times method, the each method, the loop method & the while keyword.

You have also learned how to control the loops by skipping iterations with next & breaking out of loops with break.

ruby nil

Everything You Need to Know About Nil


What is it, really?

Well, nil is just a Ruby object.

As you can see here:

There is only one nil object, with an object_id of 4 (8 in 64 bit Ruby).


Just like any other Ruby object nil has a set of methods.

Here’s the class definition from Rubinius:

Notice how all these to_something methods return an empty value (0 for numbers).

Empty hash, empty string, empty array…

The reason for this is that nil is used to represent “nothing”.

Where Do Nil Values Come From?

Many methods will return nil when you ask for some value but that value is not available. Product not found, array index out of bounds, hash key that doesn’t exist…


This will often lead to all sorts of problems since we expect our query to return a valid value instead of nil.

Like this NoMethodError exception:

To avoid this you will need to check if you have a nil value before you call a method on it.

Like this:

This is why Ruby 2.3 introduced the “safe navigator” operator (&.).


Depending on what object you are working with there are a few techniques you can use to avoid checking for nil values entirely.

For example, you can use the fetch method on Hash & Array objects.

Or you can use the Null Object Pattern in your own classes if you want to return a default value instead of nil.

Other Places Where Nil Is Lurking

You should be aware that instance variables that are undefined will return nil.

So watch out for that, it might just happen that you misspelt the name of your instance variable or you forgot to initialize it!

Another place where you can find nil is with the puts & print methods.

These two methods always return nil.

I mention this because I have seen some of my students try something like this:

Which results in numbers being [nil, nil, nil]. The solution in this case is to simply remove the puts from inside the block.

Null Object Pattern

No discussion about nil is complete without mentioning the Null Object Pattern.

In her excellent talk, “Nothing is Something“, Sandi Metz makes the point that while nil means “nothing” it can have a more specific meaning.

For example, if we write a method that finds products & we want to return a default product…

We can return a null product like this one:

Now if we have an array with a mix of real product objects & null products then all of these products will have the name method. This means that you will not get a NoMethodError exception.

Tip: If you can treat all your objects the same way, without having to check object type then you are taking advantage of Polymorphism.

These kind of objects are great for your presentation layer, but not so much for you controllers where you want to do something different if what you are looking for is not available, like showing an alert message, redirect, etc.


Another thing you need to know about nil is that it’s the only value, besides false (which is also an object), that is considered “falsy”.

Everything else in Ruby is considered true in a boolean context.

Some languages consider the number 0 as a false value, but that’s not the case in Ruby:

This is saying: “if 0 is true then print 123“.



You learned that nil is just a Ruby object that represents “nothing”.

You also learned that nil & false are the only two things in Ruby that are “falsy”. Everything else is “truthy”.

If you enjoyed this post don’t forget to share it on your favorite social networks!

ruby hidden errors

Ruby Is Hiding Errors From You!

Ruby will intentionally hide some exceptions from you.

Sometimes this can be useful. Like when using the Kernel#loop method with a block, the loop will stop when a StopIteration exception is raised.

But other times this can make your debugging sessions a lot harder.

Let’s see some examples!

Hidden Exception: Comparable Module + <=> Method

The first example involves the Comparable module & the <=> method.

Here’s the example:

Let’s talk about this example.

First we have a class named MyObject, with one attr_accessor value, and the inclusion of the Comparable module, which adds comparison methods (like ==, <, >) to our class.

These comparison methods are based on the <=> method.

Just like Enumerable methods are based on the each method.

After the class definition, we are creating two objects ( with the same value (10). Notice that even if they have the same values they are different objects, this is important.

Now if we compare these two objects mo1 & mo2 we get false


Because we have an error in our <=> method, but Ruby is hiding that error!

Look closely…

Can you spot the error?

If you found it good job! If not that’s ok 🙂

Here it is:

See this valuee?

Turns out we have a typo!

Normally we would get a NoMethodError exception & we would know what the problem is pretty quickly. But not in this example.

The good news is that since Ruby 2.3 this has changed. You can see the error now since it’s no longer hidden.

Another reason to upgrade if you are still running older Ruby versions.

Hidden Exception: Numeric Object + Coercion Method

Another example of hidden exception is with Numeric objects (Float, Integer) plus the coerce method.

Here’s an example:

This is another MyObject class, but with new methods, + & coerce.

The coerce method allows you to work with two incompatible types & transform them into the same type so they can work together.

In this case our class represents some numeric value, which could be a number of seconds, a price or anything like that…

And we want to be able to do these kind of operations:

The first one (mo1 + 20) is easy since we control the + method in our class.

But what about the Integer class?

We could change Integer’s + method to implement this, but that’s probably not a good idea 🙂

The solution?

Implement the coerce method in your own class.

One thing the + method on Integer will do is to check if your object implements this method, and if it does it will call it.

Now, remember the code example at the start of this section?

If we try to do this:

We want to see 30, because the value for mo1 is 10. But what we see is this:

Same problem as before!

An error is being hidden from us inside the coerce method.

This: mo.valuee = other

Again we have a typo, but that’s not what the error is saying!

I have good news for you, this behavior is changing in Ruby 2.5, so that will be another hidden error going away so you don’t have to worry about it.


As you can see these are good examples on why you want to avoid hiding exceptions. You can learn more about exceptions in my book, Ruby Deep Dive.

I would appreciate if you shared this post with your friends so more people can see it.

Thanks for reading!

ruby prefix trees

Learn to Implement & Use Prefix Trees in Ruby

A prefix tree (also known as a trie) is a data structure that helps you organize a word list & quickly find words that start with a specific prefix.

For example, you can find all the words in your dictionary that start with the letters “ca”, such as “cat” or “cape”.

Look at this picture:

ruby trie

This is a prefix tree.

You can follow from the root (*) to a marked node (like e and t) to find words.

In this article you will learn how to implement your own prefix tree in Ruby & how to use it to solve problems!

Prefix Tree Implementation

To implement this in Ruby I decided to use a Node class with a few attributes:

  • The value (one character)
  • The “word” variable. A true / false value which tells you if this is a valid word
  • The “next” array. This stores all the characters (as Node objects) that come after this one in the tree

Here’s the code:

Now we need a class to hold the root node & the methods for working with these nodes.

Let’s look at the Trie class:

Inside this class we have the following methods:

Both methods break down a given word into an array of characters (using the chars method).

Then we navigate the tree starting at the root & either find a character or add it.

Here are the supporting methods (also inside the Trie class):

To add a character we check if it already exists (using the find method). If it does then we return the node.

Otherwise we create it & return the new node.

Then we also have the include? method:

Now we are ready to start using our new data structure and see what we can do with it 🙂

Trie Uses & Examples

Let’s start by adding some words to our tree:

You can check if a word is included in the tree like this:

So what are some uses for this data structure?

  • Solving word games
  • Spell checking
  • Autocomplete

You will need a good dictionary to load into your tree.

I found these which may be useful to you:

Finding Prefixed Words

So in the code example I showed you before we have implemented the add & find operations.

But we also want a find_words_starting_with method.

We can do this using the “Depth First Search” (DFS) algorithm. We also need a way to keep track of the word we are looking at.

Remember that our nodes only have one character each, so we need to reconstruct the actual strings by walking over the tree.

Here’s a method that does all of that:

We use two stacks here, one for keeping track of unvisited nodes (stack) & another to keep track of the current string (prefix_stack).

We loop until we have visited all the nodes & add the value of the node to the prefix_stack. Each node holds the value for only one character, so we need to collect these characters to form a word.

The :guard_node symbol is added to the prefix_stack so we know when we are backtracking. We need this to remove characters from our string buffer (prefix_stack) at the right time.

Then if node.word is true it means we found a full word & we add it to our list of words.

Example of using this method:

If no words are found you will get an empty array:

This method can be used to implement an autocomplete feature.


You learned about prefix trees (also known as tries), a data structure used to organize a list of words into a tree. You can quickly query this tree to check if a word is valid & to find words that share the same prefix.

Don’t forget to share this post so more people can learn!