Share this post!

Category Archives for Programming

Array#zip Method

Let’s say that you want to compare two arrays, element by element so you can find the differences.

Or maybe you want to find the biggest number on every index, or you just want to merge a list of keys & a list of values to build a hash…

…the “hard way” to do this would look something like this.


That gets the job done, but it’s not very pretty, right?

In addition, you also have to stop & think for a minute to understand what’s going on.

Here’s is where Array#zip (also Enumerable#zip) comes into play!


Aha! …much better.

Do you agree?

If we are familiar with zip we will instantly understand what’s going on. And if we don’t, a quick read of the documentation (or even better, this article!) will explain it.

Another advantage of using zip is that we can easily chain it with other Enumerable methods.

Like for example, the count method:

This code returns a count of exactly how many elements are the same & in the same position.

Another trick you can use, like I mentioned before, is to merge a list of keys & values to build a hash.


Want another example?


Here it is:

This is a fancy implementation of the caesar cipher algorithm.


You learned about the Array#zip method, which allows you to “merge” two arrays & do some cool tricks with that πŸ™‚

If you enjoyed this post don’t forget to share it on your favorite social network so more people can read it!

7 Ruby Methods

7 Little-Known Ruby Methods To Help You Write Better Code

Did you know that using the right Ruby method can save you a lot of work?

The more methods you are familiar with the faster you can produce working code & the better this code will be (both in performance & quality).

That’s why today I want to introduce 7 interesting methods to you that you may not have seen before.

Looking to multiply your Ruby skills? Check out RubyGuides Pro!

Integer#digits Method (Ruby 2.4)

This is a new method introduced in Ruby 2.4 & it’s very useful if you want to work with the individual digits of an Integer.

Note: In case you are not up to speed on Ruby 2.4 changes, Fixnum & Bignum are now deprecated & both merged into Integer.

You may think that using array-like indexing may work:

But what you get are not the digits, but the binary bits that make up this number.

So pre-digits method the typical solution was to convert the number into a string, then break that string into an array of characters using the chars method, and finally convert every string back into an integer.


But in a post-digits method world, you can simply do this:

Much better, isn’t it?


The Tap Method

Sometimes you want to create an object, call some methods on it & return that same object.

You would have to do something like this:

The problem is that we have to deal with this temporary variable.

Here’s where the tap method comes to the rescue!

With tap the last example becomes this:

Notice how the temporary variable is gone, which is a good thing πŸ™‚


If you want to get multiple non-sequential values from an array or a hash you could do this:

Or you could use the values_at method:

This also works with a hash:

Hash#transform_values (Ruby 2.4)

Let’s say you have a hash & want to change all the values for some reason.

Sort of what you would do with Array#map.

The problem with map is that you will get an array-of-arrays (multi-dimensional array) instead of a hash. Also there is no Hash#map!.

So one solution could be this:

In this example we multiply each value times two.

Which results in:

Since Ruby 2.4 there is a better way to do this:

This is another of those methods coming from Rails, which is now available outside the framework πŸ™‚

Kernel#itself (Ruby 2.2)

If you told me that this method does not look very interesting at first I would agree with you.

But the reason is that you need to see some good examples.

So let’s say we have an array with repeated words & we want to count them…

While there are many ways to do this, I think this is a great case for testing out our new friend: Kernel#itself.


Notice how I also combined this with Hash#transform_values!

If transform_values is not available you can do this:


Note: The itself method shows up under the Object class in the documentation, but the method is defined on the Kernel module.


Sometimes you just need to count something.

Instead of using the typical counter + loop you can use the count method!


The array version of this method also takes a block, so you can do more complex counting.



Do you want to repeat some pattern? Or maybe you need an easy on/off toggle?

Then Enumerable#cycle might be what you are looking for!


But my favorite use for cycle is to create a “switch” or “toggle” object.

The nice thing about this is that you don’t need to check the current value of the switch to update it manually.

You can just call next & Ruby will know exactly what to do πŸ™‚


You have learned about some new useful methods: Integer#digits, Kernel#tap, Array#values_at, Hash#transform_values, Kernel#itself, Array#count, Enumerable#cycle.

If you already knew about these great! If not I hope you find them useful πŸ™‚

Enjoyed this article? Then share it with your friends so they can enjoy it too!

Build an Image Downloader in Ruby

Build an Image Downloader in Ruby

Watch this video to learn how to build an image dowloader program step-by-step using Ruby, Nokogiri & RestClient!

Starting a new project & not sure where to start?

Write down a plan!

The plan for this project:

In the video I explain every step in detail.


Note: if you want to download BIG images you may have to use a different HTTP client because RestClient will buffer the entire image into memory & you may run out of memory.

If you found this video useful make sure to share it with your friends πŸ™‚

ruby awesome print

Code Reading Adventures in The Land of Ruby

I always recommend code reading, not only because it’s good for improving your skills, but also because it’s like an adventure!

You never know what you are going to find πŸ™‚

So this time I wanted to look into the awesome_print gem.

Awesome print is a nice gem that formats your output in irb & pry to make it more readable.

For example, this is what displaying a hash with awesome_print looks like:

ruby awesome print

But how does this work?

β€œTruth can only be found in one place: the code.” ― Robert C. Martin

Ok then! Let’s take a look at the source code to find out!

Printing Awesomely

I like to start a code reading session with a quick overview of the project structure (files & folders), then I like to ask a question to focus my exploration going forward.

So the first question I came up with is:

How does awesome_print change the output of pry?

Now I put my detective hat on & make a hypothesis:

“This gem could be replacing $stdout so that it can capture the output of pry & then make it pretty.”

The problem is that this will not let you customize your pretty output, like pretty_print (from Ruby’s Standard Library) does.

Also it would not be a very flexible way to do things since we wouldn’t know what kind of object we are working with.

So the next thing I looked into is how this gem is loaded.

This will give us an entry point into the code.

Loading Awesome Print

To load awesome_print on pry you have to do this:

To find this pry! method I used the “search in directory” feature in Atom.

Here’s the method:

Well it seems like Pry allows you to modify its output by setting the value of this print variable. So this answers our initial question πŸ™‚

Want to learn more about this “proc” thing? Read “The Ultimate Guide to Blocks, Procs & Lambdas“. This is a sample chapter of my Ruby Deep Dive book.

But what is this ai method?

It’s a method defined on the Kernel module:

Since all objects include Kernel by default they will have this method available on them.

Now let’s dig a little deeper & see how this Inspector class works.

The Inspector Class

Right away after opening inspector.rb we can see a HUGE options hash inside the initialize method.

Here’s part of it:

After that we can find this code:

So this sets up two more objects which seem to handle the formatting itself & indentation of the code.

But what’s with this Thread.current thing?

Well this gives you access to the current thread. Even if you are not using threads in your application you will have one, the “main” thread.

This AP is just a constant which is defined at the top of inspector.rb:

So what’s happening here?

Awesome print is using Thread.current & the __awesome_print__ key to save some data that is only available on the current thread.

This is used to avoid problems with multi-threading.

Awesome Formatting

Let’s take a look at the output formatting code, which happens inside the AwesomePrint::Formatter class.

The way this works is that the inspector (the object created by the ai method) will call the format method.

Then this format method on the Formatter class will find the best way deal with this type of object & call another method using a bit of metaprogramming.

Here’s the method:

To understand this Formatter class we also need to take a look at the cast method:

The CORE constant is an array of symbols representing core Ruby classes & :self is just a symbol used to mean “not found” (just in this example, not in Ruby in general).

What happens is that if the object being formatted is in the “core class” list then it will get a specialized formatter.

Otherwise it will get a generic formatter.

These specialized formatters are defined under the /lib/awesome_print/formatters/ directory & include things like Array, Hash & Class.

For example, here’s the format method for classes:


You have learned about the Awesome Print gem, which lets you display objects like arrays & hashes in a nice way. You also learned how you can make a method available on every Ruby object by defining it on the Kernel module.

Hope you enjoyed this & learned something new!

Please share this post on your favorite social networks now so more people can learn πŸ™‚

ruby sinatra internals

A Quick Analysis of How Sinatra Works

What happens when you require sinatra into your project?

How does route matching work?

How are requests & responses processed?

So many questions, but so little time…

No problem!

I did the hard work for you & put together this article where I answer these questions & more!

Sinatra Initialization

It all starts with one file: sinatra.rb.

All this file does is to require main.rb, not very exciting right?

But here is where it gets more interesting.

Inside main.rb we will find a require for base.rb & we will also find the code for option parsing (port, environment, quiet mode, etc.).

Sinatra uses optparse, from Ruby’s standard library.

Another important thing happening here is the at_exit block:

This is a bit of code that will execute when the program ends.

What happens is that all your code will be read by Ruby & since you don’t have any loops, sleeps or anything like that your program will end naturally, but just before it ends the at_exit block will trigger.

When that happens Sinatra will take over & start a web server so it can handle requests:

Oh and another important thing happens here:

This defines the Sinatra DSL methods like get, post & set.

That’s why you can do this:

Request & Response Processing

Ok, so at this point we have a running server ready to accept new connections.

But what happens when a new connection is received?

Well Sinatra, just like Rails & other Ruby web frameworks, uses the Rack gem to handle all the lower level stuff.

Rack expects a call method to be available on your application. That’s just an object that you give to Rack when you initialize it.

In the case of Sinatra this object is the Sinatra::Base class.

Here’s the method:

It seems like we need to investigate the dispatch! method next to show how a request is handled.

Here’s that method:

The request in broken into 4 steps:

  1. Static files are checked first. These are files like css, js & images. This setting is enabled by default if a directory named “public” exists
  2. The before filter is run
  3. Route matching
  4. The after filter is run

Now we can dig into each step to see what happens in more detail.

Serving Static Files

The static! method is pretty simple:

This code checks if the requested file exists, then it sets the “Cache Control” HTTP header.

On the last line it calls send_file & it does just what the name says πŸ™‚

Before Filter

A before filter allows you to run code before trying to find a matching route.

This is how a filter is added:

As you can see filters is just a hash with two keys, one for each filter type.

But what is compile!?

This method returns an array with 3 elements: a pattern, an array of conditions & a wrapper.

The same method is used for generating routes (when you use a get or post block):

From this we can learn that Sinatra filters behave & work the same way as routes.

Route Matching

The next step in the request processing cycle is route matching:

This code goes over every single route that matches the request method (get, post, etc).

Route matching happens inside the process_route method:

Where pattern is a regular expression.

If a route matches both the path & the conditions then route_eval will be called, which evaluates the block (the body of your get / post route) & ends the route matching process.

This uses the unusual catch / throw mechanism for flow control.

I would recommend against it because it can be very confusing to follow the flow of code, but it’s interesting to see a real-world example of this feature in use.

Response Building

The last step of the request cycle is to prepare the response.

So where does the response go?

The invoke method gathers the response like this:

This result is assigned to the response body using the body method:

Now if we look back where we started, the call method, we will find this line of code:

This calls the finish method on @response, which is a Rack::Response object.

In other words, this will actually trigger the response to be sent to the client.

Bonus: How The Set Method Works

The set method is part of Sinatra’s DSL (Domain-Specific Language) & it lets you set configuration options anywhere in your Sinatra application.


Every time you use set Sinatra creates 3 methods (via metaprogramming):

The 3 methods are (with public_folder as example):

  • public_folder
  • public_folder=
  • public_folder?

This method will also call the setter method (public_folder=) if it already exists:

Remember that metaprogramming is not free, so I would just stick with an options hash. You don’t need those fancy methods.


You learned how Sinatra gets initialized, how it handles a request & the different steps it takes until a response can be produced.

Don’t forget to share this post with other Ruby developers so they can learn from it too πŸ™‚

1 2 3 15