RubyGuides
Share this post!

Category Archives for Programming

ruby arrays

Mastering Ruby Arrays

Ruby arrays are a fundamental data structure that is used to store data in memory. Inside a Ruby array you can store anything you want, from strings to integers and even other arrays. The elements in an array are accessed using their index, which starts at 0.

This is what an array containing the words “cat”, “dog” and “tiger” would look like:

ruby arrays

Ruby Arrays – Basic Operations

To work with an array you will have to create one first, there are multiple ways to do it.

Initialize an empty array:

Initialize an array with data:

Alternatively, you can avoid having to type the quotes for every string by doing this:

Now that we have an array the next step would be accessing the elements that it contains.

Access array element by index:

You can also use the first and last methods:

At this point you may want to add items to your array:

And finally, here is how you delete elements from your array:

There is also the shift & unshift methods, which are similar to pop/push but take or add elements in front of the array.

Here is a small cheatsheet for you:

Ruby Array to String

You can convert any array into a string by using the Array#join method.

Here’s an example:

Notice that this method takes 1 optional parameter so you can define a separator between the array elements when they are joined together.

Multidimensional Arrays

An array can be composed of other arrays, we call that a multi-dimensional array.

Example:

To access the first elements from the first sub-array you can use this syntax:

Iterating Over Ruby Arrays

Now that you have an array wouldn’t it be nice if you could enumerate its contents and print them? Well the good news is that you can!

Example: Print your array using each

Note: Most of these looping operations are available thanks to the Enumerable module, which is mixed into the Array class by default.

Example: Capitalize every word in your Array using map.

The map method doesn’t modify the array in-place, it just returns a new array with the modified elements, so we need to assign the results back to a variable. There is also a map! (notice the exclamation point) method which will modify the array directly, but in general the simpler version is preferred.

Another thing you may want to do is find all the items in your array that fit certain criteria.

Example: Find all the numbers greater than 10:

More Array Operations

There are a lot of things you can do using arrays, like sorting them or picking random elements.

You can use the sort method to sort an array, this will work fine if all you have is strings or numbers in your array. For more advanced sorting check out sort_by.

You can also remove the duplicate elements from an array, if you find yourself doing this often you may want to consider using a Set instead.

If you want to pick one random element from your array you can use the sample method:

You may also want to “slice” your array, taking a portion of it instead of the whole thing.

Example: Take the first 3 elements from the array, without changing it:

Get the size of an array:

Check if an array is empty:

Remove nil values:

Operations involving multiple arrays

If you have two arrays and want to join them you can do it like this.

You can also remove elements from one array like this, where users_to_delete is also an array:

Finally, you can get the elements that appear in two arrays at the same time:

Conclusion

Arrays are very useful and they will be a powerful ally by your side. Don’t forget to check out the documentation if you are unsure of what a method does.

If you found this useful please share this post & subscribe to my newsletter below ūüôā

Ruby Network Programming

Do you want to create custom network clients & servers in Ruby? Or just understand how that works? Then you will have to deal with sockets. Join me on this tour of ruby network programming to learn the basics, and start talking to other servers and clients using Ruby!

So what are sockets? Sockets are the end points of the communication channel, both clients and servers have to use sockets to communicate.

The way they work is very simple:
Once a connection is established you can put data into your socket and it will make its way to the other end, where the receiver will read from the socket to process incoming data.

Socket Types

There are a few types of sockets available to you, the most common — the TCP Socket — will allow you to make connections to TCP-based services like HTTP or FTP. If you have to use an UDP based protocol then you can use the UDP Socket.

The other types of sockets are a bit more esoterical, Unix sockets allow IPC (Inter-process communication) in Unix systems without the overhead of a full TCP connection.

Using Sockets in Ruby

Now that we know what sockets can do for us it is time to start using them. First, require the sockets library into your program:

To create a TCP socket you can use the TCPSocket class, as parameters you will need the destination IP address and port. This will attempt to establish a connection, if it can’t be established then you will get a Errno::ECONNREFUSED error.

You should now be able to send messages through your socket, you will have to follow the protocol you are communicating with for the other end to be able to understand you.

Many of the methods you will be using come from the parent classes of TCPSocket.

ruby network programming

To read the response from the server you can use the recv method. You need to pass the amount of bytes that you want to read from the socket as a parameter.

There is a small problem, you might not get any data back and you app will appear to be doing nothing. The reason is that if there isn’t enough data to read, your program will ‘block’.

This means it will wait until there is some data available or the server closes the connection. You may want to increase or decrease the amount of data you are reading depending on what protocol are you working with.

If blocking is an issue for you, check out the readpartial and read_nonblock methods from the IO class.

TCP Server

Let’s build a server! The process is similar to writing the client, but we will need to tell the socket to bind to an interface, then listen on it, and finally to accept incoming connections. The TCPServer class already does the first two for us.

Here is an example:

Our example server will be listening on port 8080 and greet a connecting client with a message. Notice how we can only accept one client and the program will end.

Accepting Multiple Clients

To be able to accept and respond to multiple clients, we will need a loop and some threads.

Example:

That should start a new server that keeps listening until you stop it. If you want to learn how to take this to the next level & write a web server in Ruby read this blog post.

Conclusion

You learned what TCP sockets are, how they work & how you can use some Ruby classes like TCPServer and TCPSocket to create Ruby applications that can interact with other machines on the internet.

Playing with ruby network programming is fun! Now go create something cool and share it with everyone in the comments section ūüôā

Also don’t forget to join my newsletter if you want to keep improving your Ruby skills!

Jquery tips & tricks

If you have done any web work at all you have probably used jQuery. Let’s go over some jQuery tips that you may find useful.

jquery tips

Post a form with ajax

A very common use for jQuery is AJAX. If you want to send a form via AJAX one thing you could do is this:

Aren’t all those .val() calls annoying you a bit? There is a better way to do this using the serialize function:

Toggle a div

If we want to have a “folding” div with a header that shows/hides the contents when we click on it we can do this:

First we check if the content is already showing via the display css property, then we call the .slideDown function for a little animation and change the arrow image to point down. Here is a demo.

jQuery and Coffeescript

If you decide that you would like to start using coffeescript, here is what jQuery in coffeeescript looks like:

Just pay attention to the indentation level and you should be fine ūüôā

Turbolinks + jQuery

Rails 4 comes with turbolinks enabled by default, what turbolinks does is replace the body of your site via AJAX when you click a link instead of reloading the whole page. While this will make your page appear to load faster to the user it has a small problem: it doesn’t trigger the document.ready event.

You will find that some of your js code breaks when using turbolinks because of this. Turbolinks triggers the page:load event, so we can hook our code to that, here is an example (coffeescript syntax):

Conclusion

Hate it or love it, but jQuery can be very useful and it takes care of differences between browsers (in terms of javascript stuff).

Make sure to check the docs when you have any doubts: http://api.jquery.com/. You may also find this alternative documentation useful: http://jqapi.com/.

Do you have other cool jQuery tips that you use often? Share them in the comments (you may want to use gist or jsfiddle for you code)!

How to build a parser with Ruby

Parsing is the art of making sense of a bunch of strings and converting them into something we can understand. You could just use regular expressions, but they are not always suitable for the job.

For example, it is common knowledge that parsing HTML with regular expressions is probably not a good idea. In Ruby we have nokogiri that can do this work for us, but you can learn a lot by building your own parser. Let’s get started!

Parsing with Ruby

The core of our parser is the StringScanner class. This class holds a copy of a string and a position pointer. The pointer will allow us to traverse the string in search for certain tokens. The methods we will be using are .peek, .scan_until and .getch. Another useful method is .scan (without the until).

Note:
If StringScanner is no available to you try adding require 'strscan'

I wrote two test as documentation so we can understand how this class is supposed to work:

One important thing to notice about this class is that some methods advance the position pointer (getch, scan), while others don’t (peek). At any point your can inspect your scanner (using .inspect or p) to see where it’s at.

The parser class

The parser class is where most of the work happens, we will initialize it with the snippet of text we want to parse and it will create a StringScanner for that and call the parse method:

In the test we define it like this:

We will dive in on how this class does it job in a bit, but first let’s take a look at the last piece of our program.

The Tag Class

This class is very simple, it mainly serves as a container & data class for the parsing results.

Let’s Parse!

To parse something we will need to look at our input text to find patterns. For example, we know HTML code has the following form:

There’s clearly two different components we can identify here, the tag names and the text inside the tags. If we were to define a formal grammar using the BNF notation it would look something like this:

We are going to use¬†StringScanners’s peek¬†to see if the next symbol on our input buffer is an opening tag. If that’s the case then we will call the find_tag and find_content methods on our Parser class:

The find_tag method will:

  • ‘Consume’ the opening tag character
  • Scan until the closing symbol (“>”) is found
  • Create and return a new Tag object with the tag name

Here is the code, notice how we have to chop the last character. This is because scan_until includes the ‘>’ in the results, and we don’t want that.

The next step is finding the content inside the tag, this shouldn’t be too hard since the scan_until method advances the position pointer to the right spot. We are going to use scan_until again to find the closing tag and return the tag contents.

ruby parser

Now all we need to do is to call¬†parse_element on a loop until we can’t find more tags on our input buffer.

You can find the complete code here:¬†https://github.com/matugm/simple-parser.¬†You can also look at the ‘nested_tags’ branch for the extended version that can deal with tags inside another tag.

Conclusion

Writing a parser is an interesting topic and it can also get pretty complicated at times.

If you don’t want to make your own parser from scratch you can use one of the so-called ‘parser generators’. In Ruby we have treetop and parslet.

How to write your own Caesar cipher encoder

Let’s do a little exercise together!

Have you ever heard of the Caesar cipher? Julius Caesar used this technique to conceal secret messages from his enemies. The Caesar cipher is one of the most primitive encryption techniques.

The main idea behind this system is to rotate the letters an x number¬†of positions on the alphabet. For example, with x = 1, an ‘A’ becomes a ‘B’, a ‘C’ becomes a ‘D’ and so on.

caesar cipher

So how do we implement this in code?

Glad you asked, it turns out it’s not as hard as it looks. We are going to take advantage of the fact that letters can be represented by numbers (ASCII codes), which¬†will make the job of rotating the letters a matter of just adding two numbers together.

 

Making Your Own Caesar Cipher Converter

We will start by converting an input string into an integer array:

Let’s break this down:¬†The chars method splits¬†the string into an array of characters and it returns an enumerator. As a result we can¬†call¬†map on the array. The¬†map method is very useful when we want to transform all the elements of an array in some way. The return value of map is another array with the transformed elements.

Note: this syntax requires¬†Ruby 1.9+, and it’s equivalent to:

Since we want to turn every letter into its corresponding ASCII value, we call the ord method on every element of the array. In our example, the output will be this:

 

Rotation Time

Great! The next step is to add the number of rotations we want. We can do this by using map again:

Now we can just turn the numbers back to letters, and join them, which will give us the encrypted string:

To retrieve our original string all we have to do is to apply the same procedure again, but this time shift to the left.¬†It’s important to shift by the same amount of positions we used originally; otherwise, we won’t recover our original data.

 

The Final Code & Alternative Versions

You can find the finished caesar cipher code here.

It produces all the 26 possible iterations for a given string and it also handles wrapping (the examples in the post don’t).

There is also an alternative version that uses Array#rotate

You might also like:
Ruby string formatting

1 10 11 12 13 14 16