RubyGuides
Share this post!

Category Archives for Programming

ruby case switch

The Many Uses Of Ruby Case Statements

Whenever you need to use some if / elsif statements you could consider using a Ruby case statement instead. In this post, you will learn a few different use cases and how it all really works under the hood.

ruby case

Note: In other programming languages this is known as a switch statement.

The components of a case statement in Ruby:

Keyword Description
case Starts a case statement definition. Takes the variable you are going to work with.
when Every condition that can be matched is one when statement.
else If nothing matches then do this. Optional.

Ruby Case & Ranges

The case statement is more flexible than it might appear at first sight. Let’s see an example where we want to print some message depending on what range a value falls in.

I think this code is pretty elegant compared to what the if / elsif version would look like.

Ruby Case & Regex

You can also use regular expressions as your when condition. In the following example we have a serial_code with an initial letter that tells us how risky this product is to consume.

When Not to Use Ruby Case

When you have a simple 1:1 mapping, you might be tempted to do something like this.

In my opinion it would be better to do this instead:

The hash solution is more efficient and easier to work with. Don’t you think?

How case works: the === method

You may be wondering how case works under the hood. If we go back to our first example, this is what is happening:

As you can see, the condition is reversed because Ruby calls === on the object on the left. The === is just a method that can be implemented by any class. In this case, Range implements this method by returning true only if the value is found inside the range.

This is how === is implemented in Rubinius (for the Range class):

Source: https://github.com/rubinius/rubinius/blob/master/core/range.rb#L178

Procs + Case

Another interesting class that implements === is the Proc class.

Related post: Learn more about procs & lambdas.

In this example I define two procs, one to check for an even number, and another for odd.

This is what is really happening:

Using === on a proc has the same effect as using call.

Conclusion

You have learned how the Ruby case statement works and how flexible it can be. Now it’s your turn to start making the best use of it in your own projects.

I hope you found this article useful!

Please share this post so more people can learn! 🙂

working with apis

Working with APIs

APIs are great because they let you interact with other applications, but they can be a bit intimidating if you never used one before.

In this post I will show you how to get started using your favorite APIs with Ruby!

A simple API

To use an API you will need some form of HTTP client. I like RestClient because it’s easy to use.

Example: Random Chuck Norris joke

This code sends an HTTP ‘GET’ request to the server using RestClient.get(url), then it receives a JSON string as a response which needs to be parsed by JSON.parse(response).

The parsed json is just a regular Ruby hash that we can use to get the data we want, in this case the joke.

The documentation for this API is available here.

Understanding API responses

Api responses can be pretty complex, and it can be hard to read the resulting json to find what you need. Fortunately, the json library has the jj method to pretty-print the output.

In the example above you can do this:

And this is what you get:

As you can see the json structure is more clear now. You can even go a bit further than this with the awesome_print gem, which will add some syntax coloring to the output and even better formatting than jj.

Using gems

If you want to use an API from a popular site like Github or Reddit there are gems you can use to make your life a lot easier.

Example: Using the Octokit gem to get the top 10 Ruby projects on github.

The gem’s documentation should have all the possible API calls you can do with it. Also you can use pry’s ls command to help you explore the available options.

Conclusion

APIs are fun! Now open your editor, use some APIs and create something nice 🙂

N-gram Analysis for Fun and Profit

What would you do if you are given a big collection of text and you want to extract some meaning out of it? A good start is to break up your text into n-grams.

In the fields of computational linguistics and probability, an n-gram is a contiguous sequence of n items from a given sequence of text.
– Wikipedia

For example:

If we take the phrase “Hello there, how are you?” then the unigrams (ngrams of one element) would be: "Hello", "there", "how", "are", "you", and the bigrams (ngrams of two elements): ["Hello", "there"], ["there", "how"], ["how", "are"], ["are", "you"].

If you learn better with images here is a picture of that.

ngram analysis

Downloading Sample Data

Before we can get our hands dirty we will need some sample data. If you don’t have any to work with you could download a few Wikipedia or blog articles. In this particular case, I decided to download some IRC logs from #ruby freenode’s channel.

The logs can be found here: irclog.whitequark.org/ruby

A note on data formats:

If a plain text version of the resource you want to analyze is not available, then you can use Nokogiri to parse the page and extract the data. In this case, the irc logs are available in plain text by appending .txt at the end of the url so we will take advantage of that.

This class will download and save the data for us:

This is a pretty straightforward class. We use RestClient as our HTTP client and then we save the results in a file so we don’t have to request them multiple times while we make modifications to our program.

Analyzing the data

Now that we have our data we can analyze it. Here is a simple Ngram class. In this class we use the Array#each_cons method which produces the ngrams.

Since this method returns an Enumerator we need to call to_a on it to get an Array.

Then we put everything together using a loop, Hash#merge! and Enumerable#sort_by:

Note: the get_trigrams_for_date method is not here for brevity, but you can find it on github.

This is what the output looks like:

As you can see wanting to do things is very popular in #ruby 🙂

Conclusion

Now it’s your turn, crack open your editor and start playing around with some n-gram analysis. Another way to see n-grams in action is the Google Ngram Viewer.

Natural language processing (NLP) can be a fascinating subject, wikipedia has a good overview of the topic.

You can find the complete code for this post here: https://github.com/matugm/ngram-analysis/blob/master/irc_histogram.rb

Recursion and Memoization in Ruby

Have you ever wondered if there is an alternative to iteration? Well I have good news for you: there is, and it’s called recursion.

Recursive functions are those that keep calling themselves until they hit an end goal (also known as the base case). The idea is that after each function call we make some progress towards this base case, reducing the amount of work left to be done.

Once the base case is reached, that’s the end of the recursion, and the functions start resolving.

Ruby Recursion

A classic example to start learning about recursion is calculating a factorial number, let’s see how we can do this in Ruby using both iteration and recursion.

To calculate the factorial of a number we have to multiply all the numbers from 1 to our target number. For example, the factorial of 5 is: 1 * 2 * 3 * 4 * 5 = 120.

Let’s see how we can do this using Ruby and recursion.

Example:

In this example I show you two ways to calculate a factorial number. The iterative and the recursive solution.

In the recursive solution we make progress by decreasing the number we are working with (n-1). Once (n <= 1) there are no more recursive calls, and this is what happens:

As Ruby developers we go for the iterative solution most of the time, and that’s great, but I think it’s still worth knowing how recursion works. Now let’s see another classic example: fibonacci numbers.

The Fibonacci Sequence

Leonardo Fibonacci discovered this sequence when investigating how to model the growth of rabbit population under ideal conditions. The sequence is calculated by adding up the two numbers that came before the current one.

Example:
1, 1, 2, 3, 5, 8, 13, 21

To calculate this in Ruby you can use a recursive function:

Using this function and a range you can easily calculate the first 20 Fibonacci numbers.

However, there is a problem:

Your function is doing a lot of extra work that it doesn’t need to. To illustrate this, look at the following image.

ruby recursion

In the image we can see how fib(3) is calculated five times. This makes your function really slow if you try to calculate longer Fibonacci sequences. The solution? Memoization.

Memoization: Reusing Work We Have Already Done

Wouldn’t it be great if you could just reuse the work you have already done in previous steps? We can do that using memoization.

To save our expensive calculation results we use a cache. In this case, an array will do.

Example:

First we check to see if the result is already in the cache, if it is then return it, otherwise we do the calculation and save the result.

This will run a lot faster and it will be able to calculate much bigger Fibonacci numbers.

The Limits of Recursion

As a reader kindly pointed out, the recursive solution can fail with SystemStackError: stack level too deep with big input numbers (around 7500, exact number depends on your system). If you need to calculate an even bigger number you would have to use an iterative solution.

Example:

Conclusion

Recursion is great but sometimes it can be hard to grasp. Now it’s your turn, practice makes mastery!

Please share this post if you like it & subscribe to my newsletter 🙂

Static Analysis in Ruby

If you want to know something about your source code, like the name and line number of all your methods, what do you do?

Your first idea might be to write a regexp for it, but what if I told you there is a better way?

ruby static analysis

Static analysis is a technique you can use when you need to extract information from the source code itself. This is done by converting source code into tokens (parsing).

Let’s get right into it!

Using the Parser Gem

Ruby has a parser available on the standard library, the name is Ripper. The output is hard to work with so I prefer using the fantastic parser gem. Rubocop uses this gem to do its magic.

This gem also includes a binary you can use to parse some code directly and see the resulting parse tree.

Here is an example:

The output looks like this:

This can be useful if you are trying to understand how Ruby parses some code. But if you want to create your own analysis tools you will have to read the source file, parse it and then traverse the generated tree.

Example:

The parser will return an AST (Abstract Syntax Tree) of your code. Don’t get too intimidated by the name, it’s simpler than it sounds 🙂

Traversing the AST

Now that you have parsed your code using the parser gem you need to traverse the resulting AST.

To do that you need to create a class and inherit from AST::Processor:

Then you have to instantiate this class and call the .process method:

You need to define some on_ methods. These methods correspond to the node names in the AST.

To discover what methods you need to define you can add the handler_missing method to your Processor class. You also need the on_begin method.

Here is where we are:

You have your AST and a basic processor, when you run this code you will see the node types for your AST.

Now:

You need to to implement all the on_ methods that you want to use. For example, if I want all the instance method names along with their line numbers I can do this:

When you run your program now it should print all the method names found.

Conclusion

Building a Ruby static analysis tool is not as difficult as it may look. If you want a more complete example take a look at my class_indexer gem. Now it’s your turn to make your own tools!

Please share this post if you enjoyed it! 🙂

1 9 10 11 12 13 17