RubyGuides
Share this post!

All posts by Jesus Castello

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.

Example:

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

Example:

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.

Example:

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.

Example:

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.

Example:

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.

Example:

You can stop a loop method in two ways:

  • Raising a StopIteration exception
  • Using the break keyword

Summary

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

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

NilClass

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…

Example:

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 (&.).

Example:

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.

Truthiness

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“.

Video

Summary

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 (MyObject.new) 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

Why?

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.

Summary

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!

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.

Summary

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!

ruby atom plugins

Atom Tricks, Plugins & Shortcuts for Ruby Developers

If you are using Atom for Ruby development then you probably know that there are plugins (packages in Atom) that can improve your productivity with the editor.

But Atom’s package repository has thousands of packages!

Which ones should you be using?

And on top of that, what are some useful keyboard shortcuts you can use to work faster?

If you are an Atom user you are going to love this article because that’s exactly what I cover here!

Best Atom Packages

Atom packages add new functionality to the editor. They can be installed from the editor’s interface itself.

Open your settings (CTRL + ,) & click on the “Install” tab.

atom-install-package

You can type in that search box to install the recommended packages.

Atom Runner

The first package I want to recommend is called “atom runner”.

This package allows you to run code directly inside your editor. The output will appear in a split window on the right (on the bottom if you have Atom 1.17 or newer).

It looks like this:

atom-runner

To install it simply search for its name on the package manager window & click “Install”. Then to launch it make sure your file type is set to Ruby & then press ALT + R (CTRL + R on Mac).

Note: If it doesn’t work try opening Atom from a terminal, instead of a menu or desktop icon.

If you want to increase the font size:

First open Atom’s style sheet file (with CTRL + ALT + P, type “osty”, then enter).

Then add this to the file:

Block Convert

You may want to convert between the do...end & { ... } block format. You can save yourself some work by using the “block convert” package.

With this package installed position your cursor inside a block, open the command-palette (CTRL + ALT + P) & search for “converter”, then select either “to do end” or “to curly brackets”.

This GIF demonstrates this package in action:

block-convert

Toggle Quotes

You can easily switch between single & double quotes with the “toggle-quotes” package.

To use it position your cursor inside the pair of quotes you would like to switch then press CTRL + " (or CMD + " on a Mac).

Linter Ruby

A linter is a tool that points out errors in your code.

Mostly syntax errors, so don’t expect any miracles here 🙂

This helps you find these errors faster without even having to run your tests.

You can install the “linter-ruby” package if you want to enable linting in your editor.

Other Packages

Atom Keyboard Shortcuts

Everyone loves shortcuts!

Let me give you a table with some of my favorites:

Shortcut Description
CTRL + D Multi Selection
CTRL + F Search in current file
CTRL + P Search for files in current projects (quick open)
CTRL + B Switch between open files
CTRL + ALT + 7 Toggle comments for selected code
CTRL + UP / DOWN Move current line up & down
CTRL + Shift + K Delete current line

Here’s a GIF demonstrating the multi-select feature:

atom-multi-select

You can find even more shortcuts here:

https://github.com/nwinkler/atom-keyboard-shortcuts

Atom Snippets

Snippets allow you to create expandable templates to write code faster.

For example, you can type def & the enter key.

That will create a method template for you. It will also put your cursor on the method name so you can start typing right away.

After that you can press the “tab” key & it will place your cursor inside the method body.

Pretty useful, right?

Once you get used to it you will be doing this all the time.

Here’s a list of some useful built-in Ruby snippets:

Snippet Description
if if / end
ife if / else / end
def def / end
defs def self.name / end
deft def test_ / end
cla class / end
mod module / end
ea each { … }
beg begin / rescue / end
Hash Hash.new { … }
File File.read
r attr_reader
w attr_writer
rw attr_accessor

There are also some ERB specific snippets, like = for <%= %> and - for <% %>.

Notice that your file type needs to be set to “Ruby” for these snippets to work. This happens automatically if you are editing a file with a .rb extension.

In addition, you can create your own snippets.

To do that just open your command palette (CTRL + ALT + P) & type “osni” then press enter.

A file will open where you can define your custom snippets.

A snippet looks like this:

Where the first string is the language for this snippet, then we have the name for this snippet (can be anything), and “prefix” is the actual word that will trigger the snippet, “body” is the code template.

If you have multiple snippets you don’t want to repeat the language part (.source.ruby), you just group everything under there, properly indented.

Notice the $1 here, that represents where the cursor is going to be positioned after the code snippet is inserted.

You can also have more than one of these cursor things.

Example:

When you press “tab” your cursor will go to $2, then $3, etc.

Think about what things you have to type often that are not already covered by built-in snippets, then write your own custom snippet for that.

Auto Indent

Sometimes your indentation can get out of whack & it’s a pain to fix it by hand…

Atom has you covered because it comes with an “Auto Indent” feature.

To use it select the code you want to indent, open the command palette (CTRL + ALT + P), then search for “auto”.

Built-In Git Integration

Atom includes Git integration since version 1.18.

To use it make sure the file you are editing is part of a project with an initialized git repository.

Note: You can also initialize the repository from inside the editor for new projects.

Then look at the lower right, it will say something like “3 files”.

atom-git-panel

Click on that & the Git panel will open where you can see the changes you made by clicking on each file.

Also you will be able to commit your changes by staging your changes, adding a commit message and clicking the “commit” button at the bottom of this panel.

Summary

In this article you learned how to become a more productive Ruby developer by installing useful packages, learning about keyboard shortcuts & defining custom snippets!

Like this? Don’t forget to share this article so more people can benefit from it 🙂

1 2 3 23