Ruby for Programmers – Part 6: Arrays

Oh boy, it’s been over a year since I updated this?! :(

We’re going to very quickly amp this up and get started on the real project.

Now that we’ve learned about blocks, it’s now time to learn about Arrays.

The basic Array works the way you expect:

It just stores, in order, the object you put into it. Since anything is an Object, you can even put classes inside of it.

Arrays have lots of useful functions, most of them involve blocks.

The catch with arrays is that, since everything is just pass by pointer, keep in mind the difference between modifying an array, and making a new one:

Notice how the second time function1 ran, it’s modified. array changed because the insert command modified it. This is more weird when you consider some functions copy rather than modify:

Notice how it has the same output as before? This is because Array#compact returns a new array versus modifying it. There is, in fact, an Array#compact! function that will modify rather than copy. This is important for two reasons: 1) You may want to ensure that things get copies rather than modifying the original. Or 2) You way want to modify only the original to use less memory.

As a side note, an Array is an Enumerable module (we’ll go over modules soon) so there’s two places to look for things you can do to an array:

Array specific functions
Enumerable functions

Enumerable is just a placeholder for things over anything that enumerates. An array has it’s contents, but there are other things that are also enumerable. For example, Ranges, which we introduced earlier is an Enumerable too:

And one last note for Arrays: unlike some languages which guess which type, Arrays in Ruby are only 0-first integer buckets of contiguous length. You can easily waste memory like this:

If you want to have a dictionary or associative array, look no further than the Hash (on Part 7).

Ruby for Programmers – Part 5: Functionality And Blocks

Functions can be defined using “def”:

Functions take variables:

And you can have optional function values:

However, Ruby has a special type of function parameter, the block.

What is a Block?

Blocks are functions you can define at anytime, but are also variables, which are then objects. You can use the ‘lambda’ operator to create blocks as a variable, and use the ‘call’ function to use them:

So having a function as a variable is very useful, as you can define a whole method of stuff before doing things. Note that blocks can come in two different ways, inside angle brackets like the above, or in a “do … end” statement:

And you can use the pipes to denote an argument to this function:

Notice how it raised an error when it didn’t have the right number of arguments?

Functions and Blocks

You can pass a block to a function via two methods, the ampersand or block notation:

Most of the time, we’ll be using the block notation on functions like in the last two examples. The first example uses the reserve word yield, which runs the included block. If you notice, the block isn’t an argument in the function, so you can use “block_given?” to tell if the block exists:

As we’ll show in the next section on Array, blocks are very useful.

Ruby for Programmers – Part 4: Logic and Syntax

While everything in Ruby is in Object, the logic and syntax ties them all together.

This introduces some of the reserved words and their functions. As such, they are not objects but language structure:

nil/true/false

These are actually Objects, not unlike symbols.

And they work like you think they do. And you can negate truehood/falsehood with “!” such as “!variable” like in other languages too.

If/Unless/Elsif/Else

Hopefully you’re familiar with if statements. In Ruby, if statements can be run as a one-liner or inside a set of code:

Unless is the opposite of if, and can be considered a “not if” or “nif”, etc. Essentially “if true” is the same as “unless !true”. Also in Ruby a statement is always considered true unless it is nil or false.

If you need else, then it’s available before the end.

If you need an “else if”, then use the word “elsif”. Why “elsif”? I never found that answer.

Logic

Your usual “==”, “!=”, “>”, “>=”, “<", and "<=" works just fine in if statements:

Note that those statements are functions, and you could have fun with them if you feel like. Generally speaking, the function ">” is really just this: “<=>(2) == 1″ where the function <=> returns -1,0, or 1 depending on if it’s <, =, or >.

Case

Need a switch statement? It’s called ‘case’, and does some fancy stuff, like normal bunch of equals statements:

For numbers, in can accept a Range:

(Notice the else statement?) And can even check to see class membership:

Case is one of the few newline checking statements, the result ‘when’ statement must be on other lines or it must have a ‘then’ statement if on the same line. Weird, but whatever. (Also note that else doesn’t need or want the ‘then’ statement either.)

begin/rescue/ensure

Let’s say you’re trying to do something risky and causes an error:

Okay, so we can’t “+” a number with a string. Perhaps we can rescue from it?

Whoops, we goofed. Perhaps we can get more info on that?

So we can get a variable with information about the error itself.

One last thing, you can ensure the commands are run. Ensure is run regardless if an error occurs, it’s guaranteed to run. For example, you want to ensure a file is closed regardless of error:

So regardless of that error occurring, variable still was set to 10.

Ruby for Programmers – Part 3: Strings and Symbols

Now that we’re cool with Objects, lets go back to discovering the basic built-in classes of Ruby. Strings are very important in any language, so let’s work with them!

In Ruby you can make strings in three different ways:

Output:

The reason for the different methods is if having to escape quotes roughs your style. The big difference is in how Ruby interprets the single quotes vs. double quotes. In the single quotes, it will take what you written literally, and that’s it. In double quotes, it does processing on the string to see if you meant any special codes. For example, like most languages, you can use the code “\n” to denote a new line:

So as you can see, the single quote literally wrote ‘\n’ whereas the double quote made it the new line character. Note that we’re using “print” instead of “p”. Print will print the literal characters to the screen, but ‘p’ will prettify it first.

Double quotes also have interpolation (variables within strings):

Interpolation is very useful. You will be using this a lot.

Strings are cool, but what you really want is to do things to strings, so here’s just some example methods:

Just so it isn’t obvious, you can use “#” at the beginning to denote a comment, like in most other shell-type languages. (You can’t use C-style “//” for a comment.)

For the curious, there are more things you and do to a string list in the core documentation. This just scratches the surface, see the “%” for sprintf style stuff, or the centering, or stripping.

Also, just so it’s mentioned but it’s rarely used is the multiline string:

The differences are mostly based on preference. All three support interpolation and stuff.

Symbols

There are special strings in Ruby called Symbols. Think of them as Diet Strings, as they are stored differently. While a String is a lot like a C-based char[] array where it will store the data for each one (in fact, that’s how Ruby does it internally), Symbols have their data in the symbol table and looked up from there. This is very useful for when you’re passing around configuration or column data, which you want to add headers to the data.

For example, you might see something in Ruby like:

The “:yes” part is a symbol:

If you’re going to be passing information around, a Symbol is like a giant set of enums. That way you’re not creating a new string each time you want to pass information, when an enum could suffice for what that information is. Since it has a look up table, you can just simply convert it to a string, and it auto-converts on interpolation:

You shouldn’t be using Symbols as you would a String. But it makes sense when you have a need for enums or diet strings.

There are some instances where Ruby requires a Symbol instead of a String. For example due to the Objectness of Ruby, you can actually call any method using __send__, so the following are the same:

So the first two you are familiar with. In the previous part, I showed that since everything is an object, you can call everything’s function like an object. Ruby just assumes that if you do “object1 + object2”, it just interprets it as “object1.+(object2)” because it makes the code look pretty. But you can also have it run any method using “__send__” where it requires the name of the method as a symbol. (Since method names are stored internally as a symbol. Make sense, since method names are used often enough to be necessary as an enum or diet string.)

Anyway, if you see example code that uses Symbols, use that instead. Diet Strings are very useful for performance; if you’re using a string as a information token where a random integer could provide the same information (like an enum), use a symbol.

Ruby For Programmers – Part 2: Everything is an Object

This concept should come up sooner rather than later in Ruby texts:

Everything is in Object.

Unlike some languages where certain things have certain special types (Javascript and Lua has different types, like number, string, and ‘object’, Java has ‘special’ types like int), everything in Ruby is an object. Objects can be different classes, but they all descend from Object. So for our integers earlier, they too are objects.

If you are unfamiliar with the concept of Object-Oriented Programming, just know this: Objects are buckets that have methods and instance variables. (And those instance variables are also Objects toooo!) So if you have an object, you can run a method on it. Methods are in dot notation in Ruby so:

The first statement shows the five plus five we know from earlier. The second shows that “5+5” is just short hand for “Take 5 and run the method named ‘+’ with the method arguments of ‘4’”.

Since everything is an object, there’s no real need to have outside libraries do things. For example, to round a Float, just call “round”, and it will round itself. It makes sense when you think about it, a Float should know how to round itself, and doesn’t need a helper to do it.

Objects themselves have base methods. So for example, you can find out what class something is by calling class:

So we see that “5” is an instance of the “Fixnum” class. (Also we can see that Fixnum itself, is an instance of Class, and Class is an instance of Class.)

If you want to know what class something is, just use is_a?:

So how can 5 be both a “Fixnum” and an “Integer”? That’s easy, Object Hierarchy. Let’s look at Fixnum’s ancestors:

So it appears that 5 has an ancestry when in comes to it’s classes, and thus inherits some classes in-between.

This is probably a bit too much for right now, but it’s important to know for later: the reason why we are calling methods on Strings and Arrays like we will in the future, is that they are Objects and they are having their methods called on like any other Object. Again, the difference is that some languages have types, so you need to call methods on types that know about the datatype. Example: strlen(string) in C/PHP vs. string.length in Ruby.

As a technical note, some Objects are more Objecty than others. Built-in classes, like Fixnum, String, Symbol, Array, Hash, Date, etc. have a much faster interpretation in the interpreter itself. So while they are all truly objects from a programming standpoint, the basic datatypes are stored and processed in an efficient manner.

Ruby For Programmers – Part 1: Mathematical!

Now that we’re comfortable with Ruby and it’s tools, lets start to do some basic Ruby! The first step of any language is it’s math and how to run numbers.

To insert a number, just type the number, the following are all numbers:

Again, in IRB, if you type it, it will print the result of that line. If it’s a line with just a number by itself, it’s not a useful line, but it does show it’s representation. Notice that “0x1F” results in 31? That’s because the interpreter sees that it’s in hex notation, and converts it to an integer. And the underscores in the last statement are just ignored, for code prettiness, it’s not required.

Typing numbers is great, but you can also do normal programming stuff with adding numbers and variables:

So you can set variables using the equals sign just like in most languages, and use them elsewhere, and the plus sign is used for mathematical sum. Your fairly standard operations work:

If you’re interested, there’s a whole Math library that does things like atan, sqrt, etc:

A few technical notes:

  • Integers in the machine size (32-bit, 64-bit), are represented natively, so they have good speed. (Fixint)
  • Ruby has support for really really big integers, so if you want something really large, it can do it internally, but it’s run in software so it’s slow. (Bignum)
  • Floats are always in the machine’s “double” precision, and subject to those limitations.

Ruby For Programmers – Part 0: Using Ruby

Once you have Ruby installed you should see something similar to this when you type ruby -v in Terminal:

If you don’t, then you didn’t follow the previous instructions correctly.

What you have installed is the standard Ruby interpreter. Unlike a compiled language, such as C where the code is compiled into machine code, the interpreter takes Ruby code and interprets it as it goes. This is useful as you can redefine elements in code, which we’ll explain later.

Generally speaking, when referring to “Ruby” it generally means the Ruby Language using the MRI (Matz Ruby Interpretor, also known as “C Ruby” or standard Ruby). The MRI version is denoted as 1.x.ypz. The first two numbers denote the major version (1.x), the the minor version (y), and then the patch level (z). In the above version, you are running Ruby 1.9.3, patch version 286. There are big differences between major versions, such as the upgrade 1.8 to 1.9. When searching Google for answers, be aware that some really old gems made for 1.8 may not work. (Ruby as a community tends to be updateists, so anything relevant and used will support new versions quickly.) The minor version may have some small language changes, but usually upgrades. For example, Ruby 1.9.2 -> 1.9.3 brought much faster Date/Time methods by using native code instead of Ruby code to process them. While not necessarily breaking, you may find a weird catch or two when upgrading. Patch levels fix security bugs, while not breaking any part of the language.

Other than the 1.8 to 1.9 split, and again, 1.8 is dead, there’s no language splits.

While most people focus on MRI as their interpreter, there are other interpreters out there. JRuby is a Ruby interpreter made in Java. Depending on the benchmark, it is roughly similar to MRI in performance, and has better multi-threading support. However, it relies on Java so it has all the downsides to that. There’s also MacRuby, which converts its basics to Cocoa classes (NSString, NSArray, etc.), to be better able to make Mac/iOS apps. And Rubinus, a project defined as “Ruby in Ruby”, where they’re trying to reduce the amount of C code required.

For this tutorial, we will use MRI for all our examples. As such, we’ll show the most common tools of MRI.

Now that Ruby’s installed, let’s use it and create our hello world file:

When saved as helloworld.rb, simply use this command to run:

See, now wasn’t that easy?

Now let’s say you want to try out Ruby in a more interactive fashion, then you use irb:

As you can see, it will automatically print whatever you type. And if you tell it to print, it will print the output of the print function. We’ll get in to the details of the last statement later.

There’s one more helper function of ruby that you need to know, which is gem. Any language would be nothing without having a proper reusable code library, and rubygems provides a one-stop-shop for all your needs. As of Ruby 1.9, rubygems is pre-installed. So all you need to do to install a JSON handler, JSON being a popular data format, is the following:

And the gem ‘json’ is available to you. You can use this in irb to include:

Again, the details of the language we’ll explain later, just know that because you installed the json gem, the json library is available to use through the ‘require’ statement, and allowed you to convert that ruby data into JSON.

Ruby For Programmers – Part 4294967295: Installing Ruby

Props to the first person to get the joke in the title.

The official website of Ruby is: http://ruby-lang.org. As such, that’s the only location to download Ruby for the paranoid. For our purposes though, there’s easier install methods.

So the first step of Ruby is to install it. It’s a pretty simple enough, but here’s the only part where the instructions have to split between OSes:

Windows

  1. Download and Install Ruby 1.9.3 from http://rubyinstaller.org/downloads.
  2. Download and Install the “devkit” from http://rubyinstaller.org/downloads.
  3. You can use the MinGW terminal it pre-installs if you are familiar with UNIX/POSIX commands, or you can use cmd or PowerShell if that’s your preference.
  4. In theory it should preinstall the correct PATH, so all you need to do is type “ruby -v” and get a reply. If it says “ruby 1.9.3…” then it works fine.

Mac

  1. Good News: Ruby is preinstalled. \o/
  2. Bad News: It’s the old version. So let’s make our own version using rvm:
  3. Install the Command Line Tools from https://developer.apple.com/downloads/index.action. (Optionally, it’s also available in XCode if you already have XCode installed.)
  4. Run the following command:
    curl -L https://get.rvm.io | bash -s stable --ruby=1.9.3
  5. Sit for awhile while it works.
  6. Close and restart Terminal.
  7. Run: rvm 1.9.3 --default

Linux

You probably know better than me on this. Generally speaking your package manager will have Ruby available in packages named either “ruby” or “ruby-1.9” or “ruby-1.9.3”.

When you have it installed, party.

If you can run ruby -v and have it show the Ruby version, you are good to go and started!

Programmers Who Already Program Good and Want To Ruby Good Too

Sorry for the horrible Zoolander reference. But I couldn’t resist.

As you can tell from the article title, I’m going to start a mini class on how to program in Ruby on this blog. It’s more directed to people who are already familiar with most programming concepts, so if you are learning Ruby without much programming experience, I highly suggest Ruby the Hard Way or Programming Ruby (aka the Pickaxe Book). This project will also lean towards modern Rails development, and it’s necessary skills.

Overall I think it will end with Sinatra and ActiveRecord, but I’m not sure. I really want to very slowly add in the Rails stack where all of a sudden you’re working in Rails without realizing. Such as using Sprokets manually, then setting up autoload to app/assets. I’m going to need to take a look at how to hack that up with minimal code. Anyway, off to the first steps: installing Ruby!

Note that at the top section of the each part, I’ll be writing up some trivia. Feel free to skip this, but it does have a lot of history in them, which is both interesting and significantly relevant.