Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Home

Ruby

This is the beginning of my Ruby Tutorial. Either read this, or head over to the Programming Exercises and start solving them using Ruby.

Getting started with Ruby

I have started to learn Ruby at Try Ruby Here is what I’ve learned so far.

$ ruby --version
ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin14]

The first thing we should try is printing to the screen. I’ve created a file with .rb extension. Not that it matters a lot, but I think editors and IDEs will recognize that this is a Ruby file by that extension and will be able to put nice colors on the various parts of the code.

print "Hello "
print "World\n"
puts "Hi"

puts Foo

I ran the code and got:

$ ruby examples/ruby/hello_world.rb

Hello World
Hi
examples/ruby/hello_world.rb:5:in `<main>': uninitialized constant Foo (NameError)

So calling print will print to the screen exactly what I gave to it. Calling puts will do the same, but it will also add a newline at the end of the output. If I want print to add a newline I can include \n in my string.

The last output is an error. It shows that we have to put the strings in quotes.

Comments

We can # after a statement or even as the first character of a line and everything to the right of this character (including this character) will be disregarded by Ruby. Very handy to add comments for the next person looking at the code.

Arithmetic

Part of programming is calculating stuff by using various arithmetic operations. Let’s see how does that work in Ruby:

puts 19+23   # 42
puts 19-23   # -4
puts 2*3     # 6

puts 2**3    # 8

puts 8/2     # 4
puts 3/2     # 1
puts 3/2.0   # 1.5
puts 3.0/2   # 1.5
puts 2.0/3   # 0.6666666666666666
puts 4/2.0   # 2.0



puts 3/0     # examples/ruby_arithmetic.rb:7:in `/': divided by 0 (ZeroDivisionError)
             #      from examples/ruby_arithmetic.rb:7:in `<main>'

puts 'done'

(The output of each line was added as a comment on the same line.)

The basic operation such as +, -, * work as they should.

** is the exponent operation so 2**3 = 2*2*2 = 8

At first it seems that division also works as expected, 8/2 = 4 but then it turns out that 3/2 = 1.

Apparently if both numbers in a division are whole numbers, then Ruby will also return a whole number.

On the other hand, if either (or both) the numbers are floating point numbers (they have a decimal point in them) then the result will be also floating point. Even if the value after the decimal point is 0 (4/2.0 = 2.0).

Dividing by 0 generates an exception called ZeroDivisionError and stops the program. (We did not reach the puts 'done' statement.

Ruby strings

We saw arithmetic operations on numbers, but we can also use some operations on strings:

puts "Hello".length     # 5
puts "Hello".reverse    # olleH

puts "Jar " * 2         # Jar Jar
puts 2 * 3              # 6

puts "2".to_s * 3       # 222
puts 2.to_s * 3         # 222

puts 2 * "Jar " 
 #   examples/ruby_strings.rb:7:in `*': String can't be coerced into Fixnum (TypeError)
 #      from examples/ruby_strings.rb:7:in `<main>'

Becasue in Ruby everything is an object, there are certain methods we can run on a string. For example the length method will return the number of characters in the string.

The reverse method will return the characters in reverses order.

We can use the * multiplicator on a string. It will return (and puts will display) a new string in which we have several (in this case 2) copies of the original string.

If we want to have 3 copies of the number 2, we have a number of options.

puts 2 * 3 # 6

this one is not doint that, as the * between two numbers will multiply them.

We can put the number 2 in quotes:

puts "2".to_s * 3 # 222

or we can use the to_s to conver the number to a string.

puts 2.to_s * 3 # 222

This will be much more interesting once we start to use variables.

Finally, if we new that we want 3 copies of the number 2, we could have just written “222” without trying to use all kinds of Ruby operations.

Absolutely finally, let’s see what happens if we swap the string and the number in this multiplication operation:

puts 2 * "Jar "

We get an excpetion:

    examples/ruby/strings.rb:7:in `*': String can't be coerced into Fixnum (TypeError)
       from examples/ruby/strings.rb:7:in `<main>'

I guess we cannot do that.

timestamp: 2015-02-08T15:30:01 tags:

  • print
  • puts
  • length
  • reverse
  • to_s

Variables and Variable Interpolation in Ruby

Using simple values as in introduction to Ruby article will get you bored soon. It is much more interesting to create names that can hold values and then use those names. These names we call “variables”, because usually their content can be changes.

Variable nanes can starte with any lower~ or uppercase letter or underscore. They can contain lowercase, uppercase letters, digits, and underscores. Once we have assigned value to a variable we can use puts to print the content of the variable

We can also use the variables for other operations. For example to add them together:

a = 23
b = 19

c = a + b
puts c

$ ruby add_numbers.rb
42

With this we can create a variable containing the name of the user, and then welcome that user by concatenating together two strings and the variable using + as string addition.

name = "Foo Bar"

puts "Hello " + name + ", how are you?"
$ ruby hello_name.rb
Hello Foo Bar, how are you?

Interpolation or variable embedding

There is however another way to create the same result:

name = "Foo Bar"

puts "Hello #{name} how are you?"

Here we used the #{} construct to tell ruby, instead of the word ‘name’ it needs to take the content of the variable called ‘name’ and include that in the string.

Variable declaration in Ruby

In Ruby there is no need to declare a variable. It just has to appear in an assignment before it is used in any other expression.


x = 23
puts x

puts y
y = 19
$ ruby bad_variable.rb
23
bad_variable.rb:5:in `<main>': undefined local variable or method `y' for main:Object (NameError)

timestamp: 2015-10-06T10:50:01 tags:

  • puts
  • #{}

Arrays in Ruby

Arrays in Ruby

Arrays in Ruby are similar to arrays in Perl and lists in Python. They can hold a bunch of unrelated values in slots indexed from 0 up.

Similar to the other two dynamic languages, arrays in ruby can also grow and shrink as the user needs them. There is no need for special memory handling.

Arrays in Ruby are created by comma separated values assigned to a variable:

names = 'Foo', 'Bar', 'Baz'

We can access them using an index after the name of the variable:

puts names[0]    # Foo
puts names[1]    # Bar
puts names[2]    # Baz

We can fetch the size of the array, by using the length method:

puts names.length   # 3

If we try to access an element by an index that is not in the array, Ruby will print nothing (an empty sting):

puts names[3]       # (nothing)

On the other hand, just like in Perl, Ruby arrays understand negative indexes. They access the array from the other end:

puts names[-1]      # Baz

Assign to array element

We can assign a value to any of the indexes in the array. It overwrites the old value. Then we can fetch the current value from the array.

names[1] = 'Happy'
puts names[1]     # Happy

Not only that, but we can also assign to indexes that were not part of the array previously. The array will automatically grow as we can see from the value returned by the length method.

names[3] = 'Moo'
puts names[3]       # Moo
puts names.length   # 4

We can even assign value to an index further away. The array will be enlarged and the intermediate elements will remain empty. (They will have nil in them.)

names[6] = 'Far Away'
puts names[6]       # Far Away
puts names.length   # 7
puts names[5]       # (nothing)

Going over the elements of the array

There are a number of ways to iterate over the elements of an array.

Pretty Print values for debugging

Similar to the Data::Dumper module in Perl, Ruby has the pp library for Pretty Printing data structures. It makes it easy to print out the content of an array:

require 'pp'
pp names        # ["Foo", "Happy", "Baz", "Moo", nil, nil, "Far Away"]

push

If we want to add one or more elements to an array, we can use the push method to do that.

names.push 'Hello', 'World'
pp names     # ["Foo", "Happy", "Baz", "Moo", nil, nil, "Far Away", "Hello", "World"]

pop

The opposite operation is called pop. It will fetch the last element of an array, remove it from the array and return it to be used in an assignment:

last = names.pop
pp names    # ["Foo", "Happy", "Baz", "Moo", nil, nil, "Far Away", "Hello"]
puts last   # World
pp last     # "World"

We can even pass a parameter to pop to indicate how many element we wish to remove from the end of the array. In that case (even if we passed 1), the returned value will be an array of the removed elements:

last = names.pop 2
pp names    # ["Foo", "Happy", "Baz", "Moo", nil, nil]
pp last     # ["Far Away", "Hello"]

shift

shift moves the content of the array to the left. The left-most element is removed from the array and returned to be used in an assignment (or any other operation). It can be thought as similar to pop just at the beginning of the array.

first = names.shift
pp names    # ["Happy", "Baz", "Moo", nil, nil]
puts first  # Foo

unshift

unshift is the opposite of shift. It puts one or more elements to the beginning of the array. This methods is rarely used.

names.unshift 'Zorg', 'Morg'
pp names    # ["Zorg", "Morg", "Happy", "Baz", "Moo", nil, nil]

Full example


names = 'Foo', 'Bar', 'Baz'

puts names[0]   # Foo
puts names[1]   # Bar
puts names[2]   # Baz

puts names.length   # 3

puts names[3]       # (nothing)


puts names[-1]      # Baz

names[1] = 'Happy'
puts names[1]       # Happy


names[3] = 'Moo'
puts names[3]       # Moo
puts names.length   # 4

names[6] = 'Far Away'
puts names[6]       # Far Away
puts names.length   # 7
puts names[5]       # (nothing)

require 'pp'
pp names     # ["Foo", "Happy", "Baz", "Moo", nil, nil, "Far Away"]

names.push 'Hello', 'World'
pp names     # ["Foo", "Happy", "Baz", "Moo", nil, nil, "Far Away", "Hello", "World"]

last = names.pop
pp names    # ["Foo", "Happy", "Baz", "Moo", nil, nil, "Far Away", "Hello"]
puts last   # World
pp last     # "World"


last = names.pop 2
pp names    # ["Foo", "Happy", "Baz", "Moo", nil, nil]
pp last     # ["Far Away", "Hello"]


first = names.shift
pp names    # ["Happy", "Baz", "Moo", nil, nil]
puts first  # Foo


names.unshift 'Zorg', 'Morg'
pp names    # ["Zorg", "Morg", "Happy", "Baz", "Moo", nil, nil]

timestamp: 2015-10-29T14:31:23 tags:

  • []
  • array
  • push
  • pop
  • shift
  • unshift

For loop in Ruby (iterating over array elements)

In Ruby the C-like for-loop is not in use. Instead of that people usually iterate over the elements of an array using the each method.


names = ['Foo', 'Bar', 'Baz']

puts names
puts


names.each { |item|
    puts item
}
puts

names.each do |item|
    puts item
end

In this example we have an array with 3 elements. At first we just printed the array as it is. We got the values on on every line. That can be useful for debugging, but it we want to go over the elements we need some kind of a loop.

The each method allows us to iterate over the elements of the array. On every iteration the variable between the pipes (item in our case) will receive the current value.

Here we have 2 examples. The first one uses curly braces to mark the beginning and the end of the block, the other one uses the do - end pair.

$ ruby examples/ruby/iterating_on_array.rb 
Foo
Bar
Baz

Foo
Bar
Baz

Foo
Bar
Baz

There is another way to iterate over the elements, but it can have a nasty side-effect and thus not recommended.

names = ['Foo', 'Bar', 'Baz']

for item in names 
    puts item
end

the code looks ok, the result is ok

$ ruby examples/ruby/for_loop_on_array.rb 
Foo
Bar
Baz

But if we have used the item variable earlier, then this for loop will overwrite that other item variable with the last value seen in the loop.

names = ['Foo', 'Bar', 'Baz']

item = 'Moose'

for item in names 
    puts item
end

puts
puts item


Note how, after the loop has finished the variable item holds ‘Baz’.

$ ruby examples/ruby/for_loop_on_array_global.rb 
Foo
Bar
Baz

Baz

timestamp: 2015-02-10T13:00:01 tags:

  • each
  • for

Range in Ruby

Ruby has two operators to generate a range of values. .. is inclusive and ... is exclusive.

..

for i in 0..3
    puts i
end

Will generate

0
1
2
3

including the beginning and the end similar to how the range in Perl works.

…

If we use 3 dots instead of two, then the range will include the lower limit, but not the higher limit. Similar to how range in Python works.

for i in 0...3
    puts i
end

0
1
2

reverse range

If the limit on the left hand side is higher than on the right hand side, the range operator won’t return any values.

for i in 7 .. 4
    puts i
end

It does not return any value.

As an alternative we can create a growing list of number and then call the reverse method on them. For this however first we need to convert the rnage to an array:

for i in (4..7).to_a.reverse
    puts i
end

printing:

7
6
5
4

Range of letters

In additonal to ceating ranges of numbers, Ruby can also create a range of letters:

for i in 'a'..'d'
   puts i
end
a
b
c
d

Range of characters

Not only that, but we can use any two characters in the visible part of the ASCII table:

for i in 'Z'..'a'
   puts i
end
Z
[
\
]
^
_
`
a

Range with variables

We can also use variables as the lower and upper limits:

x = 3
y = 6 
for i in x .. y
   puts i
end

timestamp: 2015-09-24T23:30:01 tags:

  • ..
  • …
  • to_a
  • reverse

ARGV - the command line arguments of a Ruby program

When you run a script written in Ruby you can put all kinds of values on the command line after the name of the script:

For example:

ruby code.rb abc.txt def.txt qqrq.txt

or like this:

ruby code.rb Hello --machine big -d -tl

The question though, how can the Ruby program know what was given on the command line?

Ruby maintains an array called ARGV with the values passed on the command line. We can access the elements of this array, just as any other array:

ARGV[0] is going to be the first value after the name of the script.

We can iterate over the elements either directly with a for loop:

for arg in ARGV
   puts arg
end

or iterating over the range of indexes, and accessing the elements using that index.

for i in 0 ... ARGV.length
   puts "#{i} #{ARGV[i]}"
end

$ ruby command_line_argv_with_index.rb foo bar --machine big
0 foo
1 bar
2 --machine
3 big

Verifying the number of arguments

For a simple input validation we can check the length of the ARGV array. Report if we have not received enough arguments and exit the program early.

if ARGV.length < 2
  puts "Too few arguments"
  exit
end

puts "Working on #{ARGV}";

Running this script we get:

$ ruby command_line_argv_check_length.rb one
Too few arguments

$ ruby command_line_argv_check_length.rb one two
Working on ["one", "two"]

Values received on the command line are strings

In this snippet of code we first check if we got exactly 2 parameters and we do, we add them together:

if ARGV.length != 2
  puts "We need exactly two arguments"
  exit
end

puts ARGV[0] + ARGV[1]
ruby command_line_argv_add.rb 23 19
2319

The result might not be surprising to you if you know that the values the user passes on the command line are received as strings. Eeven if they are actually numbers. If we would like to use them as number we have to convert them using to_i:

if ARGV.length != 2
  puts "We need exactly two arguments"
  exit
end

puts ARGV[0].to_i + ARGV[1].to_i

$ ruby command_line_argv_add_numbers.rb 23 19
42

timestamp: 2015-10-06T22:30:01 tags:

  • ARGV
  • to_i