The Complete Magazine on Open Source

A few fundamentals of Ruby programming

/ 6876 0

Ruby Prgramming

Ruby is an open source, general programming language that has been influenced by Perl, Smalltalk, Eiffel, Ada and Lisp. It has an elegant syntax, and is focused on simplicity and productivity. Ruby is easy to learn and works on the principle of ‘writing more with less’.

Programming languages and spoken languages are quite similar; both have one or more categories. A few programming language categories you might have heard of include imperative, object-oriented, functional or logic-based. Ruby is a powerful and dynamic open source, object-oriented language created by a developer known as Matz, and runs on almost all platforms such as Linux, Windows, MacOS, etc. Every programmer’s first computer program is usually the ‘Hello World Program’, as shown below.


Are you, now, more interested in Ruby? Ruby is one of the easiest languages to learn as it focuses on the productivity of program development. It is a server-side scripting language and has features that are similar to those of Smalltalk, Perl and Python.

Ruby and Ruby on Rails
Ruby is a programming language while Ruby on Rails, or simply Rails, is a software library that extends the Ruby programming language. Rails is a software framework dependent on the Ruby programming language for creating Web applications.

Web applications can also be written in Ruby, but writing a fully functional Web application from scratch in Ruby is a daunting task. Rails is a collection of pre-written code that makes writing Web applications easier and helps make them simpler to maintain.

Still confused? Think of how a pizza is made. You simply spread the tomato sauce on the pizza base, top it with the veggies and spread the grated cheese. But where did the pizza base come from? It’s easier to get it from the grocery store instead of baking your own using flour and water. In this case, the Ruby programming language is the flour and water. By learning Ruby, you are a step closer to Rails and can create Web applications like Twitter one day.

Application domains
Text processing: Ruby can be embedded into HTML, and has a clean and easy syntax that allows a new developer to learn it very quickly and easily.

CGI programming: Ruby can be used to write Common Gateway Interface (CGI) scripts. It can easily be connected to databases like DB2, MySQL, Oracle and Sybase.

Network programming: Network programming can be fun with Ruby’s well-designed socket classes.

GUI programming: Ruby supports many GUI tools such as Tcl/Tk, GTK and OpenGL.
XML programming: Ruby has a rich set of built-in functions, which can be used directly into XML programming.

Prototyping: Ruby is often used to make prototypes that sometimes become production systems by replacing the bottlenecks with extensions written in C.

Programming fundamentals
1. Instructions and interpreters
Ruby is an ‘interpreted’ programming language, which means it can’t run on your processor directly, but has to be fed into a middleman called the ‘virtual machine’ or VM. The VM takes in Ruby code on one side, and speaks natively to the operating system and the processor on the other. The benefit of this approach is that you can write Ruby code once and, typically, execute it on many different operating systems and hardware platforms. A Ruby program can’t run on its own; you need to load the VM. There are two ways of executing Ruby with the VM — through IRB and through the command line.

Running Ruby from the command line: This is the durable way of writing Ruby code, because you save your instructions into a file. This file can then be backed up, transferred, added to source control, etc.

We might create a file named my_program.rb like this:

class Sample
def hello
puts “Hello World”

Then we could run the program in the terminal like this:

$ruby my_program.rb
Hello World

When you run ruby my_program.rb you’re actually loading the Ruby virtual machine, which in turn loads your my_program.rb.
Running Ruby from IRB: IRB stands for ‘interactive Ruby’ and is a tool you can use to interactively execute Ruby expressions read from the standard input.
The irb command from your shell will start the interpreter.

2. Variables
Programming is all about creating abstractions, and in order to create an abstraction we must be able to assign names to things. Variables are a way of creating a name for a piece of data. In some languages you need to specify what type of data (like a number, word, etc) can go in a certain variable. Ruby, however, has a flexible type system where any variable can hold any kind of data.
Creating and assigning a variable: In some languages you need to ‘declare’ a variable before you assign a value to it. Ruby variables are automatically created when you assign a value to them. Let’s try an example:

irb(main):001:0> a = 5
=> 5
irb(main):002:0> a
=> 5

The line a = 5 creates the variable named ‘a’ and stores the value ‘5’ into it.
Right side first: In English, we read left to right, so it’s natural to read code left to right. But when evaluating an assignment using the single equals (=), Ruby actually evaluates the right side first. Take the following example:

irb(main):001:0> b = 10 + 5
b => 15

The 10 + 5 is evaluated first, and the result is given the name ‘b’.
Flexible typing: Ruby’s variables can hold any kind of data, and can even change the type of data they hold. For instance:

irb(main):001:0> c = 20
=> 20
irb(main):002:0> c = “hello”
=> “hello”

The first assignment gave the name ‘c’ to the number 20. The second assignment changed ‘c’ to the value ‘hello’.

3. Strings
In the real world, strings tie things up. Programming strings have nothing to do with real-world strings. Programming strings are used to store collections of letters and numbers. That could be a single letter like ‘a’, a word like ‘hi’, or a sentence like ‘Hello my friends’.

Writing a string: A Ruby string is defined as a quote sign (“) followed by a zero or more letters, numbers or symbols, which are followed by a closing quote sign (”). The shortest possible string is called the empty string: “”. It’s not uncommon for a single string to contain paragraphs or even pages of text.
Common string methods: Let’s experiment with strings and some common methods in IRB.
The .length method tells you how many characters (including spaces) are in the string:

irb(main):001:0> greeting = “hello everyone!”
=> “hello everyone!”
irb(main):002:0> greeting.length
=> 15

Often, you’ll have a string that you want to break into parts. For instance, imagine you have a sentence stored in a string and want to break it into words:

irb(main):001:0> sentence = “this is my sample sentence”
=> “this is my sample sentence”
irb(main):002:0> sentence.split
=> [“this”, “is”, “my”, “sample”, “sentence”]

The .split method gives you back an array, which we’ll learn about later in this article. It cuts the string wherever it encounters a space (“ ’’) character.

Combining strings and variables: Very often, we want to combine the value of a variable with a string. For instance, let’s start with this example string:
“Good morning, Frank!”
When we put that into IRB, it just spits back the same string. If we were writing a proper program, we’d want it to greet users with their name rather than ‘Frank’. What we need to do is combine a variable with the string. There are two ways of doing this.

String concatenation: The simplistic approach is called ‘string concatenation’, which is joining strings together with the plus sign:

irb(main):001:0> name = “Frank”
irb(main):002:0> puts “Good morning, ” + name + “!”

In the first line, we set up a variable to hold the name. In the second line, we print the string “Good morning”, combined with the value of the variable name and the string “!”.

String interpolation: The second approach is to use string interpolation, where we stick data into the middle of a string. String interpolation only works on a double-quoted string. Within the string we use the interpolation marker #{}. Inside those brackets, we can put any variable or Ruby code, which will be evaluated, converted to a string, and output in that spot of the outer string. Our previous example could be rewritten like this:

irb(main):001:0> name = “Frank”
irb(main):002:0> puts “Good morning, #{name}!”

If you compare the outputs, you’ll see that they give the same results. The interpolation style tends to have fewer characters to type, and fewer open/close quotes and plus signs to forget.

4. Numbers
There are two basic kinds of numbers: integers (whole numbers) and floats (have a decimal point). Integers are much easier for both you and the computer to work with. You can use normal math operations with integers including +, -, /, and *. Integers have a bunch of methods to help you do math-related things, which you can see by calling 5.methods.

Repeating instructions: A common pattern in other languages is the ‘for’ loop, used to repeat an instruction a set number of times. For example, in JavaScript you might write:

for(var i = 0; i < 5; i++)
console.log(“Hello, World”);

‘For’ loops are common, but they’re not very readable. Because Ruby’s integers are objects, they have methods. One of these is the .times method to repeat an instruction a set number of times.
You can rewrite the above loop in Ruby, as follows:

5.times do
puts “Hello, World!”

In this example, we’re using both the .times method and what’s called a block.

5. Blocks
Blocks are a powerful concept used frequently in Ruby. Think of them as a way of bundling up a set of instructions for use elsewhere.

Starting and ending blocks: You just saw a block used with the .times method on an integer. The block starts with the keyword ‘do’ and ends with the keyword ‘end’. The do/end style is always acceptable.

Bracket blocks: When a block contains just a single instruction, though, we often use the alternate markers ‘{’ and ‘}’ to begin and end the block:

5.times{ puts “Hello, World!” }

6. Arrays
Usually, when we’re writing a program it’s because we need to deal with a collection of data. There are lots of cool things to do with an array. Here are a few examples.
.sort: The sort method will return a new array where the elements are sorted. If the elements are strings, they’ll come back in alphabetical order. If they’re numbers, they’ll come back in ascending value order. Try these:

irb(main):001:0> one = [“this”, “is”, “an”, “array”]
irb(main):002:0> one.sort
irb(main):003:0> one

You can rearrange the order of the elements using the sort method. You can iterate through each element using the each method. You can mash them together into one string using the join method. You can find the address of a specific element by using the index method. You can ask an array if an element is present with the include method. We use arrays whenever we need a list in which the elements are in a specific order.

7. Hashes
A hash is a collection of data, in which each element of the data is addressed by a name.  A hash is an unordered collection, where the data is organised into ‘key/value pairs’. Hashes have a more complicated syntax that takes some getting used to:

irb(main):001:0> produce = {“apples” => 3, “kiwi” => 1}
irb(main):002:0> puts “There are #{produce[‘apples’]} apples in the fridge.”

Simplified hash syntax: We commonly use symbols as the keys of a hash. When all the keys are symbols, then there is a shorthand syntax that can be used:

irb(main):001:0> produce = {“apples” => 3, “kiwi” => 1}
irb(main):002:0> puts “There are #{produce[:apples]} apples in the fridge.”

Notice that the keys end with a colon rather than beginning with one, even though these are symbols.

8. Conditionals
Conditional statements evaluate to true or false. The most common conditional operators are == (equal), > (greater than), >= (greater than or equal to), < (less than), and <= (less than or equal to).
Conditional branching/instructions: Why do we have conditional statements? Most often, it’s to control conditional instructions, especially if/elseif/else structures. Let’s write an example by adding a method like this in IRB:

def water_status(minutes)
if minutes < 7
puts “The water is not boiling yet”
elsif minutes == 7
puts “It’s just barely boiling”
elsif minutes == 8
puts “It’s boiling!”
puts “Hot! Hot! Hot!”

Try running the method with water_status(5), water_status(7), water_status(8) and water_status(9).
Understanding the execution flow: When the minutes are 5, here is how the execution goes: “Is it true that 5 is less than 7? Yes, it is; so print the line The water is not boiling yet”.

When the minutes are 7, it goes like this: “Is it true that 7 is less than 7? No. Next, is it true that 7 is equal to 7? Yes, it is; so print the line It’s just barely boiling”.

When the minutes are 8, it goes like this: “Is it true that 8 is less than 7? No. Next, is it true that 8 is equal to 7? No. Next, is it true that 8 is equal to 8? Yes, it is; so print the line It’s boiling!”.

Lastly, when the total is 9, the execution goes like this: “Is it true that 9 is less than 7? No. Next, is it true that 9 is equal to 7? No. Next, is it true that 9 is equal to 8? No. Since none of these are true, execute the else and print the line Hot! Hot! Hot!.