RubyGuides
Share this post!

Category Archives for Programming

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.

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.

Example:

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

Much better, isn’t it?

Video:

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 πŸ™‚

Array#values_at

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.

Example:

Notice how I also combined this with Hash#transform_values!

If transform_values is not available you can do this:

Video:

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

Array#count

Sometimes you just need to count something.

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

Example:

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

Video:

Enumerable#cycle

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!

Example:

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 πŸ™‚

Summary

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.

Code:

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:

Summary

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.

Example:

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.

Summary

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 πŸ™‚

ruby linked list

Practical Linked List in Ruby

This is the 3rd entry in the “Practical Computer Science in Ruby” series! Today we are going to talk about linked list.

So what’s a linked list?

Like the name says, a linked list is a way to store data in a list format (thanks, Captain Obvious!).

The “linked” part comes from the fact that data is stored in a node & these nodes are linked to each other in a sequential manner.

linked list

How is this different from an array?

Linked List vs Array

A linked list has different performance characteristics than an array. That’s one reason why you may want to pick one over the other.

This means that a linked list can be more efficient for certain tasks than an array.

In a linked list there is no indexing, no random access, meaning that you can’t just reach out for an item in the middle of the list.

You have to start at the “head” of the list & follow the links until you find the node you want or until the end of the list.

On the other hand, removing (or adding) an item from the middle of a linked list is a lot faster.

All you have to do is change the “next” pointer for one node.

But if you want to delete an element from the middle of an array you will leave a gap & to close that gap you have to move all the elements on the right of the deleted element.

array delete

Not very efficient if you have to do this often!

If we want to insert in the middle of an array we have to move all the array elements to create an empty space.

Let’s see a code example:

Note: There is also a built-in Array#insert method, but I wanted to show you how this method works.

If you are wondering about the actual performance impact of inserting an item in the middle of a list here’s a benchmark:

Big difference here, but it also depends a lot on the size of the LinkedList since we have to search for the node.

Another way to compare two data structures is to look at a time complexity table (this assumes you don’t have to search a node for insertion & deletion):

Data Structure Access Search Insertion Deletion
Array O(1) O(n) O(n) O(n)
Linked List O(n) O(n) O(1) O(1)

Looking for real-world applications?

Here’s a pull request by Aaron Patterson where he speeds up Ruby Gems by using a linked list:

https://github.com/rubygems/rubygems/pull/1188

Linked List Implementation

Ruby doesn’t include a LinkedList class so we need to create our own.

We want the following operations to be available:

  • append (to the end of the list)
  • append_after
  • delete
  • find

Here’s one possible implementation:

Notice that this particular implementation doesn’t keep track of the tail & instead it finds the tail when appending a new item. This makes the append operation linear time (O(n)). In the video below I show you another implementation where I append the elements at the front.

And here is our node class:

We can use it like this:

This is a basic “Singly-Linked List” implementation.

You also have other types of linked list:

  • Doubly-Linked List
  • Circular Linked List

In the doubly-linked list every node has two pointers: one to the next node & another to the previous node.

This allows for more flexibility when searching the list, but also requires extra work when making changes to the list.

A circular linked list is the same than a doubly-linked list, but the last node is connected to the head node.

Video

Summary

You have learned about linked list, a data structure which you could consider if you are doing a lot of adding & removing of elements in the middle of an array.

It could also come up in a coding interview, so it’s worth learning even if it’s just for that.

Don’t forget to share this post using the buttons below so more people can benefit from this knowledge πŸ™‚