Introduction to Ruby

Everything you need to know to start programming in Ruby.

The above code creates a single string, whose contents are the values from an_array, with “, ” between each pair of elements.

Hashes are similar to arrays, except that instead of storing values using an ordered, numeric index, they are stored with keys, for example:

my_hash = {'a' => 1, 'b' => 2}

We can now retrieve either of the two values, by using its key:


The above lines of code return the numbers 1 and 2, respectively. As with arrays, we can store any object as a value in a hash; it doesn't have to be an integer.

We can retrieve the keys and values of a hash with the Hash#keys and Hash#values methods, respectively. (Later, I explain how to iterate over the keys and values to retrieve contents from a hash.) Sometimes, however, we simply want to know if a particular key exists in a hash. This is easily accomplished with Hash#has_key?, which takes a string as a parameter and returns a Boolean value. The following code thus would return true:



Every language lets us execute code conditionally. In Ruby, this normally is done with an if statement. Consider the following (somewhat contrived) example:

if server_status == 0
print "Server is in single-user mode"
elsif server_status == 1
print "Server is being fixed "
elsif network_response == 3
print "Server is available"
print "Network response was unexpected value '#{network_response}'"

Notice that Ruby does not require parentheses around the condition. And although the condition does not have to return a Boolean value, Ruby will produce a warning if you try to use = (that is, assignment) in the condition, rather than == (that is, comparison). The == comparison operator works on all objects; there are no separate text comparison and numeric comparison operators as in Perl. This is true for < and > also, which can be used to compare strings as well as numbers. Finally, Ruby does not use opening or closing braces; instead, it closes the conditionally executed block of code with end.

As with Perl, you can use if and unless as suffixes to make a statement conditional:

print "We won!" if our_score > their_score
print "Here is your change of #{amount_paid - price}!"
    unless amount_paid <= price

You also can do things like:

if inputs.length < 4
    print "Not enough inputs!\n"

And, also:

if not my_hash.has_key?("debug")
    print "Debugging is inactive.\n"


Ruby does have some looping operators, such as for and while. But the real fun and excitement is in doing things such as this:

5.times {print "hello\n"}

Think about it—we're invoking a method on a number, using the standard Ruby method-invocation syntax. The times method for integers executes a block of code a particular number of times. So, the above line of code executes five times, printing the word hello (followed by a new line) each time.

Blocks can take parameters as well, between pipe (|) characters:

5.times {|iteration| print "Hello, iteration number #{iteration}.\n"}

We similarly can iterate over the elements of an array with the each method:

an_array = ['Reuven', 'Shira', 'Atara', 'Shikma', 'Amotz']
an_array.each {|name| print "#{name}\n"}

A variation of the each method, called each_with_index, requires a block that takes two parameters. The first parameter is the item, and the second is the index:

an_array.each_with_index {|name, index| print "#{index}: #{name}\n"}

At a certain point, blocks become difficult to read in this syntax. Ruby provides an alternate syntax, replacing the curly braces with do and end:

an_array.each_with_index do |name, index|

We can iterate over a hash in several ways. One way is to use the type of iteration that Perl and Python programmers have used for years, getting the hash's keys (via Hash#keys, which returns an array) and then grabbing the value that goes with the key:

state_codes = {'Illinois' => 'IL', 'New York' => 'NY',
               'New Jersey' => 'NJ', 'Massachusetts' => 'MA',
               'California' => 'CA'}

state_codes.keys.each do |state|
    print "State code for #{state} is #{state_codes[state]}.\n"

Of course, we might want to sort the keys before iterating over them:

state_codes.keys.sort.each do |state|

Ruby provides an easier way to perform this task, the each_pair method:

state_codes.each_pair do |state, code|
    print "State code for #{state} is #{code}.\n"



Comment viewing options


Inspired by You

noman13bd's picture

Ruby On Rails installation on Windows
Ruby on Rails installation in Ubuntu
autocompleter example in RoR
live Validation for RoR

Ismail Muhammad Noman

I'm only just starting to

Anonymous's picture





Nice and fast intro (plus two typos)

Praxis's picture


I did notice these two typos:



Regardless of this, I did enjoy reading this intro.