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â end end s=Sample.new s.hello
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:
C:\Users\Administrator>irb 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:
C:\Users\Administrator>irb 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:
C:\Users\Administrator>irb 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:
C:\Users\Administrator>irb 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:
C:\Users\Administrator>irb 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:
C:\Users\Administrator>irb 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:
C:\Users\Administrator>irb 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!â end
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:
C:\Users\Administrator>irb 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:
C:\Users\Administrator>irb 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:
C:\Users\Administrator>irb 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!â else puts âHot! Hot! Hot!â end end
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!.