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:


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.


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.


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 >.


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.)


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:


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.


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.