Showing posts with label Ruby on Rails. Show all posts
Showing posts with label Ruby on Rails. Show all posts

Step By Step Ruby on Rails Tutorials For Beginners

Ruby tutorial

This is a Ruby tutorial. In this tutorial you will learn Ruby language. The tutorial is suitable for beginners.

Table of contents

Ruby

Ruby is a dynamic, reflective, general-purpose object-oriented programming language. The original author is a Japanese programmer Yukihiro Matsumoto. Ruby first appeared in 1995. Ruby supports various programming paradigms. This includes object orientation, reflection, imperative and reflective programming.
Continue Reading

Input and output in Ruby

In this part of the Ruby tutorial, we will talk about Input & output operations in Ruby. The input is any data that is read by the program, either from a keyboard, file or other programs. The output is data that is produced by the program. The output may go to the screen, to a file or to another program.
Input & output is a large topic. We bring forward some examples to give you a general idea of the subject. Several classes in Ruby have methods for doing input/output operations. For example Kernel, IO, Dir or File.

Writing to console

Ruby has several methods for printing output on the console. These methods are part of the Kernel module. Methods of the Kernel are available to all objects in Ruby.
#!/usr/bin/ruby

print "Apple "
print "Apple\n"

puts "Orange"
puts "Orange"
The print and puts methods produce textual output on the console. The difference between the two is that the latter adds a new line character.
print "Apple "
print "Apple\n"
The print method prints two consecutive "Apple" strings to the terminal. If we want to create a new line, we must explicitly include the newline character. The newline character is '\n'. Behind the scenes. the print method actually calls the to_s method of the object being printed.
puts "Orange"
puts "Orange"
The puts method prints two strings to the console. They are on a separate line. The method includes automatically the newline character.
$ ./printing.rb
Apple Apple
Orange
Orange
Output of the printing.rb script file.

According to the Ruby documentation, the print method is an equivalent to the $stdout.print. The $stdout is a global variable which holds the standard output stream.
#!/usr/bin/ruby

$stdout.print "Ruby language\n"
$stdout.puts "Python language"
We print two lines using the $stdout variable.

Ruby has another three methods for printing output.
#!/usr/bin/ruby

p "Lemon"
p "Lemon"

printf "There are %d apples\n", 3

putc 'K'
putc 0xA
In the example, we present p, printf and putc methods.
p "Lemon"
The p calls the inspect method upon the object being printed. The method is useful for debugging.
printf "There are %d apples\n", 3
The printf method is well known from the C programming language. It enables string formatting.
putc 'K'
putc 0xA
The putc method prints one character to the console. The second line prints a newline. The 0xA is a hexadecimal code for the newline character.
$ ./printing3.rb 
"Lemon"
"Lemon"
There are 3 apples
K
Output of the example.

Printing data to the console using the kernel methods is a shortcut. A convenient way to print data. The following example shows a more formal way to print data to the terminal.
ios = IO.new STDOUT.fileno
ios.write "ZetCode\n"
ios.close
In the example, we open a standard output stream and write a string into it.
ios = IO.new STDOUT.fileno
The new method returns a stream to which we can write data. The method takes a numeric file descriptor. The STDOUT.fileno gives us the file descriptor for the standard output stream. We could also simply write 2.
ios.write "ZetCode\n"
We write a string to the opened stream.
ios.close
The input stream is closed.

On Unix systems the standard terminal output is connected to a special file called /dev/tty. By opening it and writing to it, we write to a console.
#!/usr/bin/ruby

fd = IO.sysopen "/dev/tty", "w"
ios = IO.new(fd, "w")
ios.puts "ZetCode"
ios.close
A small example in which we write to a /dev/tty file. This only works on Unix.
fd = IO.sysopen "/dev/tty", "w"
The sysopen method opens the given path, returning the underlying file descriptor number.
ios = IO.new(fd, "w")
The file descriptor number is used to open a stream.
ios.puts "ZetCode"
ios.close
We write a string to the stream and close it.

Reading input from console

In this section, we will create some code examples that will deal with reading from the console.
The $stdin is a global variable that holds a stream for the standard input. It can be used to read input from the console.
#!/usr/bin/ruby

inp = $stdin.read
puts inp
In the above code, we use the read method to read input from the console.
inp = $stdin.read
The read method reads data from the standard input, until it reaches the end of the file. The EOF is produced by pressing Ctrl + D on Unix or Ctrl + Z on Windows.
$ ./reading.rb
Ruby language
Ruby language
When we launch a program without a parameter, the script reads data from the user. It reads until we press Ctrl + D or Ctrl + Z.
$ echo "ZetCode" | ./reading.rb
ZetCode

$ ./input.rb < stones
Garnet
Topaz
Opal
Amethyst
Ruby
Jasper
Pyrite
Malachite
Quartz
The script can read data from another program or a file, if we do some redirections.

The common way to read data from the console is to use the gets method.
#!/usr/bin/ruby

print "Enter your name: "
name = gets
puts "Hello #{name}"
We use the gets method to read a line from the user.
name = gets
The gets method reads a line from the standard input. The data is assigned to the name variable.
puts "Hello #{name}"
The data that we have read is printed to the console. We use interpolation to include the variable in the string.
$ ./readline.rb
Enter your name: Jan
Hello Jan
Sample output.

In the following two scripts, we will discuss the chompmethod. It is a string method. It removes white spaces from the end of the string, if present. It is useful when doing input operations. The method name and usage comes from the Perl language.
#!/usr/bin/ruby

print "Enter a string: "
inp = gets

puts "The string has #{inp.size} characters"
We read a string from a user and calculate the length of the input string.
$ ./nochomp.rb 
Enter a string: Ruby
The string has 5 characters
The message says that the string has 5 characters. It is because it counts the newline as well.

To get the correct answer, we need to remove the newline character. This is a job for the chomp method.
#!/usr/bin/ruby

print "Enter a string: "
inp = gets.chomp

puts "The string has #{inp.size} characters"
This time we use we cut the newline character with the chompmethod.
$ ./chomp.rb 
Enter a string: Ruby
The string has 4 characters
The Ruby string has indeed 4 characters.

Files

From the official Ruby documentation we learn that the IO class is the basis for all input and output in Ruby. The File class is the only subclass of the IO class. The two classes are closely related.
#!/usr/bin/ruby

f = File.open('output.txt', 'w')
f.puts "The Ruby tutorial"
f.close
In the first example, we open a file and write some data to it.
f = File.open('output.txt', 'w')
We open a file 'output.txt' in a write mode. The open method returns an io stream.
f.puts "The Ruby tutorial"
We used the above opened stream to write some data. The puts method can be used to write data to a file as well.
f.close
At the end the stream is closed.
$ ./simplewrite.rb
$ cat output.txt
The Ruby tutorial
We execute the script and show the contents of the output.txt file.

We will have a similar example, which will show additional methods in action.
#!/usr/bin/ruby

File.open('langs', 'w') do |f|

f.puts "Ruby"
f.write "Java\n"
f << "Python\n"

end
If there is a block after the open method, then Ruby passes the opened stream to this block. At the end of the block, the file is automatically closed.
f.puts "Ruby"
f.write "Java\n"
f << "Python\n"
We use three different methods to write to a file.
$ ./simplewrite2.rb
$ cat langs
Ruby
Java
Python
We execute the script and check the contents of the langs file.

In the second example, we show a few methods of the File class.
#!/usr/bin/ruby

puts File.exists? 'tempfile'

f = File.new 'tempfile', 'w'
puts File.mtime 'tempfile'
puts f.size

File.rename 'tempfile', 'tempfile2'

f.close
The example creates a new file named 'tempfile' and calls some methods.
puts File.exists? 'tempfile'
The exists? method checks, if a file with a given name already exists. The line returns false, because we have not yet created the file.
f = File.new 'tempfile', 'w'
The file is created.
puts File.mtime 'tempfile'
The mtime method gives us the last modification time of the file.
puts f.size
We determine the file size. The method returns 0, since we have not written to the file.
File.rename 'tempfile', 'tempfile2'
Finally, we rename the file using the rename method.
$ ./testfile.rb
false
2011-11-05 16:19:36 +0100
0
Sample output.

Next, we will be reading data from the files on the disk.
#!/usr/bin/ruby

f = File.open("stones")

while line = f.gets do
puts line
end

f.close
This is a simple script, that will open a file called stones and print it contents line by line to the terminal.
f = File.open("stones")
We open a 'stones' file. The default mode is a read mode. The 'stones' file contains nine names of valued stones; each on a separate line.
while line = f.gets do
puts line
end
The gets method reads a line from the I/O stream. The while block ends when we reach the end of file.
$ ./readlines2.rb
Garnet
Topaz
Opal
Amethyst
Ruby
Jasper
Pyrite
Malachite
Quartz
Output of the example.

The next example will read data from a file.
#!/usr/bin/ruby

fname = 'alllines.rb'

File.readlines(fname).each do |line|
puts line
end
This script is another way, how we can read contents of a file. The code example will print its own code to the terminal.
File.readlines(fname).each do |line|
puts line
end
The readlines reads all lines from the specified file and returns them in the form of an array. We go through the array with the each method and print the lines to the terminal.
$ ./alllines.rb
#!/usr/bin/ruby

fname = 'alllines.rb'

File.readlines(fname).each do |line|
puts line
end
Output of the example.

Directories

In this section, we work with directories. We have a Dir class to work with directories in Ruby.
#!/usr/bin/ruby

Dir.mkdir "tmp"
puts Dir.exists? "tmp"

puts Dir.pwd
Dir.chdir "tmp"
puts Dir.pwd

Dir.chdir '..'
puts Dir.pwd
Dir.rmdir "tmp"
puts Dir.exists? "tmp"
In the script we use four methods of the Dir class.
Dir.mkdir "tmp"
The mkdir method makes a new directory called 'tmp'.
puts Dir.exists? "tmp"
With the exists? method, we check if a directory with a given name exists in the filesystem.
puts Dir.pwd
The pwd method prints a current working directory. It is a directory, where we have launched the script.
Dir.chdir '..'
The chdir method changes to another directory. The '..' directory is the parent directory of the current working directory.
Dir.rmdir "tmp"
puts Dir.exists? "tmp"
Finally, we remove a directory with the rmdir method. This time the exists? method returns false.
$ ./dirs.rb
true
/home/vronskij/programming/ruby/io
/home/vronskij/programming/ruby/io/tmp
/home/vronskij/programming/ruby/io
false
Output of the example.

In the second example, we retrieve all entries of a directory. Both files and directories.
#!/usr/bin/ruby

fls = Dir.entries '.'
puts fls.inspect
The entries method returns all entries of a given diretory.
fls = Dir.entries '.'
puts fls.inspect
We get the array of files and directories of a current directory. The '.' character stands for the current working directory in this constext. The inspect method gives us a more readable representation of the array.
$ ./allfiles.rb
["putc.rb", "simplewrite.rb", "readlines2.rb", "fileexists.rb~" ...
In the output we can see an array of files and directories.

The third example works with a home directory. Every user in a computer has a unique directory assigned to him. It is called a home directory. It is a place where he can place his files and create his own hierarchy of directories.
#!/usr/bin/ruby

puts Dir.home
puts Dir.home 'root'
The script prints two home directories.
puts Dir.home
If we do not specify the user name, then a home directory of a current user is returned. The current user is the owner of the script file. Someone, who has launched the script.
puts Dir.home 'root'
Here we print the home directory of a specific user. In our case the superuser.
$ ./homedir.rb
/home/vronskij
/root
Sample output.

Executing external programs

Ruby has several ways to execute external programs. We will deal with some of them. In our examples we will use well known Linux commands. Readers with Windows or Mac can use commands specific for their systems.
#!/usr/bin/ruby

data = system 'ls'
puts data
We call a ls command, which lists directory contents.
data = system 'ls'
The system command executes an external program in a subshell. The method belongs to the Kernel Ruby module.
$ ./system.rb
allfiles.rb characters.rb fileexists.rb homedir.rb~ ...
A sample output.

We show another two ways of running external programs in Ruby.
#!/usr/bin/ruby

out = `pwd`
puts out

out = %x[uptime]
puts out

out = %x[ls | grep 'readline']
puts out
To run external programs we can use backticks `` or %x[] characters.
out = `pwd`
Here we execute the pwd command using backticks. The command returns the current working directory.
out = %x[uptime]
Here we get the output of the uptime command, which tells how long a system is running.
out = %x[ls | grep 'readline']
We can use also a combination of commands.
$ ./system2.rb
/home/vronskij/programming/ruby/io
22:50:50 up 5:32, 1 user, load average: 0.46, 0.44, 0.45
readline.rb
readline.rb~
readlines2.rb
readlines2.rb~
Sample output.

We can execute a command with the open method. The method belongs to the Kernel module. It creates an IO object connected to the given stream, file, or subprocess. If we want to connect to a subprocess, we start the path of the open with a pipe character (|).
#!/usr/bin/ruby

f = open("|ls -l |head -3")
out = f.read
puts out
f.close

puts $?.success?
In the example, we print the outcome of the ls -l | head -3commands. The combination of these two commands return the first three lines of the ls -l command. We also check the status of the child subprocess.
f = open("|ls -l |head -3")
We connect to a subprocess, created by these two commands.
out = f.read
puts out
We read and print data from the subprocess.
f.close
We close the file handler.
puts $?.success?
The $? is a special Ruby variable, which obtains the status of the last executed child process. The success?method returns true, if the child process ended OK, false otherwise.
$ ./system3.rb
total 148
-rwxr-xr-x 1 vronskij vronskij 57 2011-10-30 23:33 allfiles.rb
-rwxr-xr-x 1 vronskij vronskij 58 2011-10-30 23:33 allfiles.rb~
true
Sample output.

Redirecting standard output

Ruby has predefined global variables for standard input, standard output and standard error output. The $stdout is the name of the variable for the standard output.
#!/usr/bin/ruby

$stdout = File.open "output.log", "a"

puts "Ruby"
puts "Java"

$stdout.close
$stdout = STDOUT

puts "Python"
In the above example, we redirect a standard output to the output.log file.
$stdout = File.open "output.log", "a"
This line creates a new standard ouput. The standard output will now flow to the ouput.log file. The file is opened in an append mode. If the file does not exist yet, it is created. Otherwise it is opened and the data is written at the end of the file.
puts "Ruby"
puts "Java"
We print two strings. The strings will not be shown in the terminal as usual, they will be appended to the output.log file.
$stdout.close
We close the handler.
$stdout = STDOUT

puts "Python"
We use a predefined standard constant STDOUT to recreate the normal standard ouput. The "Python" string is printed to a console.
In this part of the Ruby tutorial, we worked with input and output operations in Ruby.
Continue Reading

Regular expressions in Ruby

In this part of the Ruby tutorial, we will talk about Regular expressions in Ruby.
Regular expressions are used for text searching and more advanced text manipulation. Regular expressions are built into tools like grep, sed, text editors like vi, emacs, programming languages like Tcl, Perl, Python. Ruby has a built-in support for regular expressions too.
From another point of view, regular expression is a domain specific language for matching text.
A pattern is a regular expression, that defines the text, we are searching for or manipulating. It consists of text literals and metacharacters. The pattern is placed inside two delimiters. In Ruby these are // characters. They inform the regex function where the pattern starts and ends.
Here is a partial list of metacharacters:
.Matches any single character.
*Matches the preceding element zero or more times.
[ ]Bracket expression. Matches a character within the brackets.
[^ ]Matches a single character, that is not contained within the brackets.
^Matches the starting position within the string.
$Matches the ending position within the string.
|Alternation operator.
In Ruby language, Regexp class is used to develop regular expressions. There are also two shorthand ways to create regular expressions. The following example will show them.
#!/usr/bin/ruby

re = Regexp.new 'Jane'
p "Jane is hot".match re

p "Jane is hot" =~ /Jane/
p "Jane is hot".match %r{Jane}
In the first example, we show three ways of applying regular expressions on a string.
re = Regexp.new 'Jane'
p "Jane is hot".match re
In the above two lines, we create a Regexp object cointaining a simple regular expression text. Using the match method, we apply this regular expression object on the "Jane is hot" sentence. We check, if the word 'Jane' is inside the sentence.
p "Jane is hot" =~ /Jane/
p "Jane is hot".match %r{Jane}
These two lines do the same. Two forward slashes // and the %r{} characters are shorthands for the more verbose first way. In this tutorial, we will use the forward slashes. This is a de facto standard in many languages.
$ ./regex.rb
#<MatchData "Jane">
0
#<MatchData "Jane">
In all three cases there is a match. The match method returns a matched data, or nil if there is no match. The =~ operator returns the first character of the matched text, or nil otherwise.

The dot character

The dot character is a regular expression character, which matches any single character. Note that there must be some character; it may not be omitted.
#!/usr/bin/ruby

p "Seven".match /.even/
p "even".match /.even/
p "eleven".match /.even/
p "proven".match /.even/
In the first example, we will use the match method to apply regular expression on strings. The match method returns the matched data on success or nil otherwise.
p "Seven".match /.even/
The "Seven" is the string on which we call the match method. The parameter of the method is the pattern. The /.even/ regular pattern looks for a text that starts with an arbitrary character followed by the 'even' characters.
$ ./dot.rb
#<MatchData "Seven">
nil
#<MatchData "leven">
nil
From the output we can see which strings did match and which did not.

As we have said above, if there is a dot character, there must be an arbitrary character. It may not be omitted. What if we wanted to search for a text, in which the character might be omitted? In other words, we want a pattern for both 'seven' and 'even'. For this, we can use a ? repetition character. The ? repetition character tells that the previous character may be present 0 or 1 time.
#!/usr/bin/ruby

p "seven".match /.even/
p "even".match /.even/
p "even".match /.?even/
The script uses the ? repetition character.
p "even".match /.even/
This line prints nil since the regular expression expects one character before the 'even' string.
p "even".match /.?even/
Here we have slightly modified the regular expression. The '.?' stands for no character or one arbitrary character. This time there is a match.
$ ./dot2.rb
#<MatchData "seven">
nil
#<MatchData "even">
Example output.

Regular expression methods

In the previous two examples, we have used the match method to work with regular expressions. There are other methods where we can apply regular expressions.
#!/usr/bin/ruby

puts "motherboard" =~ /board/
puts "12, 911, 12, 111"[/\d{3}/]

puts "motherboard".gsub /board/, "land"

p "meet big deep nil need".scan /.[e][e]./
p "This is Sparta!".split(/\s/)
The example shows some methods that can work with regular expressions.
puts "motherboard" =~ /board/
The =~ is an operator that applies the regular expression on the right to the string on the left.
puts "12, 911, 12, 111"[/\d{3}/]
Regular expressions can be placed between the square brackets following the string. This line prints the first string which has three digits.
puts "motherboard".gsub /board/, "land"
With the gsub method we replace a 'board' string with a 'land' string.
p "meet big deep nil need".scan /.[e][e]./
The scan method looks for matches in the string. It looks for all occurences, not just the first one. The line prints all strings that match the pattern.
p "This is Sparta!".split(/\s/)
The split method splits a string using a given regular expression as a separator. The \s character type stands for any whitespace character.
$ ./apply.rb
6
911
motherland
["meet", "deep", "need"]
["This", "is", "Sparta!"]
Output of the apply.rb script.

Special variables

Some of the methods that work with regular expressions activate a few special variables. They contain last matched string, string before the last match and string after the last match. These variables make the job easier for a programmer.
#!/usr/bin/ruby

puts "Her name is Jane" =~ /name/

p $`
p $&
p $'
The example shows three special variables.
puts "Her name is Jane" =~ /name/
In this line we have a simple regular expression matching. We look for a 'name' string inside the 'Her name is Jane' sentence. We use the =~ operator. This operator also sets three special variables. The line returns number 4, which is the position on which the match starts.
p $`
The $` special variable contains the text before the last match.
p $&
The $& has the matched text.
p $'
And the $' variable contains the text after the last match.
$ ./svars.rb
4
"Her "
"name"
" is Jane"
Output of the example.

Anchors

Anchors match positions of characters inside a given text. We will deal with three anchoring characters. The ^ character matches the beginning of the line. The $ character matches the end of the line. The \b character matches word boundaries.
#!/usr/bin/ruby

sen1 = "Everywhere I look I see Jane"
sen2 = "Jane is the best thing that happened to me"

p sen1.match /^Jane/
p sen2.match /^Jane/

p sen1.match /Jane$/
p sen2.match /Jane$/
In the first example, we work with the ^ and the $ anchoring characters.
sen1 = "Everywhere I look I see Jane"
sen2 = "Jane is the best thing that happened to me"
We have two sentences. The word 'Jane' is located at the beginning of the first one and at the end of the second one.
p sen1.match /^Jane/ 
p sen2.match /^Jane/
Here we look if the word 'Jane' is at the beginning of the two sentences.
p sen1.match /Jane$/ 
p sen2.match /Jane$/
Here we look for a match of a text at the end of the sentences.
$ ./anchors.rb
nil
#<MatchData "Jane">
#<MatchData "Jane">
nil
These are the results.

A common request is to include only a match of a whole word. By default we count any match, including a match in larger or compound words. Let us look at an example to clarify things.
#!/usr/bin/ruby

text = "The cat also known as the domestic cat is a small,
usually furry, domesticated, carnivorous mammal."

p text.scan /cat/

p $`
p $&
p $'
We have a sentence. And within this sentence, we look for a string cat. With the help of the scan method, we look for all 'cat' strings in the sentence. Not just the first occurence.
text = "The cat also known as the domestic cat is a small, 
usually furry, domesticated, carnivorous mammal."
The problem is that inside the text there are three 'cat' strings. In addition to the 'cat' referring to the mammal there is also a match inside the word 'domesticated'. Which is not what we are looking for in this case.
$ ./boudaries.rb
["cat", "cat", "cat"]
"The cat also known as the domestic cat is a small, \nusually furry, domesti"
"cat"
"ed, carnivorous mammal."
Runnning the example shows three matches. And the special variables show the text before and after the match in the 'domesticated' adjective. This is not what we want. In the next example, we will improve our regular expression to look only for whole word matches.

The \b character is used to set boundaries to the words we are looking for.
#!/usr/bin/ruby

text = "The cat also known as the domestic cat is a small,
usually furry, domesticated, carnivorous mammal."

p text.scan /\bcat\b/

p $`
p $&
p $'
The example is improved by including the \b metacharacter.
p text.scan /\bcat\b/
With the above regular expression, we look for 'cat' strings as whole words. We do not count subwords.
$ ./boudaries2.rb
["cat", "cat"]
"The cat also known as the domestic "
"cat"
" is a small, \nusually furry, domesticated, carnivorous mammal."
This time there are two matches. And the special variables show correctly the text before and after the last match.

Character classes

We can combine characters into character classes with the square brackets. A character class matches any character, that is specified in the brackets. The /[ab]/ pattern means a or b, as opposed to /ab/ which means a followed by b.
#!/usr/bin/ruby

words = %w/ sit MIT fit fat lot pad /

pattern = /[fs]it/

words.each do |word|
if word.match pattern
puts "#{word} matches the pattern"
else
puts "#{word} does not match the pattern"
end
end
We have an array of six three letter words. We apply a regular expression on the strings of the array with a specific character set.
pattern = /[fs]it/
This is the pattern. The pattern looks for 'fit' and 'sit' strings in the array. We use either 'f' or 's' from the character set.
$ ./classes.rb
sit matches the pattern
MIT does not match the pattern
fit matches the pattern
fat does not match the pattern
lot does not match the pattern
pad does not match the pattern
There are two matches.

In the next example we will further explore the character classes.
#!/usr/bin/ruby

p "car".match %r{[abc][a][rs]}
p "car".match /[a-r]+/
p "23af 433a 4ga".scan /\b[a-f0-9]+\b/
The example has three regular expressions with character classes.
p "car".match %r{[abc][a][rs]}
The regular expression in this line consists of three character classes. Each is for one character. The [abc] is either a, b or c. The [a] is only a. The third one, [rs], is either r or s. There is a match with the 'car' string.
p "car".match /[a-r]+/
We can use a hyphen - character inside the character class. The hyphen is a metacharacter denoting an inclusive range of characters. In our case, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, r characters. Since the character class applies only for one character, we also use the + repetition character. This says that the previous character from the character set may be repeated one or more times. The 'car' strings meets these conditions.
p "23af 433a 4ga".scan /\b[a-f0-9]+\b/
In this line, we have a string consisting of three substrings. With the scan method we check for hexadicimal numbers. We have two ranges. The first, [a-f] stands for characters from a to f. The second one, [0-9] stands for numbers 0 to 9. The + specifies that these characters can be repeated multiple times. Finally, the \b metacharacters create boundaries, which accept only strings that consists of only these characters.
$ ./classes2.rb
#<MatchData "car">
#<MatchData "car">
["23af", "433a"]
Example output.

If the first character of a character class is a caret (^) the class is inverted. It matches any character except those which are specified.
#!/usr/bin/ruby

p "ABC".match /[^a-z]{3}/
p "abc".match /[^a-z]{3}/
In the example, we use a caret character inside a character class.
p "ABC".match /[^a-z]{3}/
We look for a string having 3 letters. These letters may not be letters from a to z. The "ABC" string matches the regular expression, because all three characters are uppercase characters.
p "abc".match /[^a-z]{3}/
This "abc" string does not match. All three characters are in the range, that is excluded from the search.
$ ./caret.rb
#<MatchData "ABC">
nil
Example output.

Quantifiers

A quantifier after a token or group specifies how often that preceding element is allowed to occur.
 ?     - 0 or 1 match
* - 0 or more
+ - 1 or more
{n} - exactly n
{n,} - n or more
{,n} - n or less (??)
{n,m} - range n to m
The above is a list of common quantifiers.
#!/usr/bin/ruby

p "seven dig moon car lot fire".scan /\w{3}/
p "seven dig moon car lot fire".scan /\b\w{3}\b/
In the example, we want to select those words, that have exactly three characters. The \w character is a word character, and \w{3} means three times the prevoius word character.
p "seven dig moon car lot fire".scan /\w{3}/
The first line simply cuts first three characters from each string. Which is not exactly what we want.
p "seven dig moon car lot fire".scan /\b\w{3}\b/
This is an improved search. We put the previous pattern between the \b boundary metacharacter. Now the search will find only those words, that have exactly three characters.
$ ./nchars.rb
["sev", "dig", "moo", "car", "lot", "fir"]
["dig", "car", "lot"]
Output of the example.

The {n,m} is a repetition structure for strings having from n to m characters.
#!/usr/bin/ruby

p "I dig moon lottery it fire".scan /\b\w{2,4}\b/
In the above example we choose words that have two, three of four characters. We again use the boundary \b metacharacter to choose whole words.
$ ./rchars.rb
["dig", "moon", "it", "fire"]
The example prints an array of words having 2-4 characters.

In the next example, we will present the ? metacharacter. A character followed by a ? is optional. Formally, the character preceding the ? may be present once or 0 times.
#!/usr/bin/ruby

p "color colour colors colours".scan /colou?rs/
p "color colour colors colours".scan /colou?rs?/

p "color colour colors colours".scan /\bcolor\b|\bcolors\b|\bcolour\b|\bcolours\b/
Say we have a text in which we want to look for the colour word. The word has two distinct spellings, english 'colour' and american 'color'. We want to find both occurences, plus we want to find their plurals too.
p "color colour colors colours".scan /colou?rs/
The colou?rs pattern finds both 'colours' and 'colors'. The u character, which precedes the ? metacharacter is optional.
p "color colour colors colours".scan /colou?rs?/
The colou?rs? pattern makes the u and s characters optional. And so we find all four colour combinations.
p "color colour colors colours".scan /\bcolor\b|\bcolors\b|\bcolour\b|\bcolours\b/
The same request could be written using alternations.
$ ./qmark.rb
["colors", "colours"]
["color", "colour", "colors", "colours"]
["color", "colour", "colors", "colours"]
Example output.

In the last example of this section, we will show the + metacharacter. It allows the preceding character to be repeated 1 or more times.
#!/usr/bin/ruby

nums = %w/ 234 1 23 53434 234532453464 23455636
324f 34532452343452 343 2324 24221 34$34232/

nums.each do |num|
m = num.match /[0-9]+/

if m.to_s.eql? num
puts num
end
end
In the example, we have an array of numbers. Numbers can have one or more number characters.
nums = %w/ 234 1 23 53434 234532453464 23455636
324f 34532452343452 343 2324 24221 34$34232/
This is an array of strings. Two of them are not numbers, because they contain non-numerical characters. They must be excluded.
nums.each do |num|
m = num.match /[0-9]+/

if m.to_s.eql? num
puts num
end
end
We go through the array and apply the regular expression on each string. The expression is [0-9]+, which stands for any character from 0..9, repeated 0 or multiple times. Note that by default, the regular expression looks for substrings as well. In the 34$34232 the engine considers 34 to be a number. The \b boundaries do not work here, because we do not have concrete characters and the engine does not know, where to stop looking. This is why we have included an if condition in the block. The string is considered a number only if the match is equal to the original string.
$ ./numbers.rb
234
1
23
53434
234532453464
23455636
34532452343452
343
2324
24221
These values are numbers.

Case insensitive search

We can perform a case insensitive search. A regular expression can be followed by an option. It is a single character that modifies the pattern in some way. In case of a case insensitive search, we apply the i option.
#!/usr/bin/ruby

p "Jane".match /Jane/
p "Jane".match /jane/
p "Jane".match /JANE/

p "Jane".match /jane/i
p "Jane".match /Jane/i
p "Jane".match /JANE/i
The example show both case sensitive and case insensitive search.
p "Jane".match /Jane/
p "Jane".match /jane/
p "Jane".match /JANE/
In these three lines the characters must exactly match the pattern. Only the first line gives a match.
p "Jane".match /jane/i
p "Jane".match /Jane/i
p "Jane".match /JANE/i
Here we use the i option, which followes the second / character. We do case insensitive search. All three lines do match.
$ ./icase.rb
#<MatchData "Jane">
nil
nil
#<MatchData "Jane">
#<MatchData "Jane">
#<MatchData "Jane">
Output of the example.

Alternation

The next example explains the alternation operator (|). This operator enables to create a regular expression with several choices.
#!/usr/bin/ruby

names = %w/Jane Thomas Robert Lucy Beky
John Peter Andy/

pattern = /Jane|Beky|Robert/

names.each do |name|

if name =~ pattern
puts "#{name} is my friend"
else
puts "#{name} is not my friend"
end
end
We have 8 names in the names array. We will look for a multiple combination of strings in that array.
pattern = /Jane|Beky|Robert/ 
This is the search pattern. It says, Jane, Beky and Robert are my friends. If you find either of them, you have found my friend.
$ ./alternation.rb
Jane is my friend
Thomas is not my friend
Robert is my friend
Lucy is not my friend
Beky is my friend
John is not my friend
Peter is not my friend
Andy is not my friend
Output of the script.

Subpatterns

We can use square brackets () to create subpatterns inside patterns.
#!/usr/bin/ruby

p "bookworm" =~ /book(worm)?$/
p "book" =~ /book(worm)?$/
p "worm" =~ /book(worm)?$/
p "bookstore" =~ /book(worm)?$/
We have the following regex pattern: book(worm)?$. The (worm) is a subpattern. Only two strings can match. Either 'book' or 'bookworm'. The ? character follows the subpattern, which means, that the subpattern might appear 0, 1 time in the final pattern. The $ character is here for the exact end match of the string. Without it, words like bookstore, bookmania would match too.
#!/usr/bin/ruby

p "book" =~ /book(shelf|worm)?$/
p "bookshelf" =~ /book(shelf|worm)?$/
p "bookworm" =~ /book(shelf|worm)?$/
p "bookstore" =~ /book(shelf|worm)?$/
Subpatterns are often used with alternation. We can create then multiple word combinations. For example (shelf|worm) subpattern enables us to search for words 'bookshelf' and 'bookworm'. And with the ? metacharacter also for 'book'.
$ ./subpatterns2.rb
0
0
0
nil
Output. The last subpattern does not match. Remember, that the 0s do not mean that there was no match. For the =~ operator, it is the index of the first character of the matched string.

Email example

In the final example, we create a regex pattern for checking email addresses.
#!/usr/bin/ruby

emails = %w/ luke@gmail.com andy@yahoo.com 23214sdj^as
f3444@gmail.com /

pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/

emails.each do |email|

if email.match pattern
puts "#{email} matches"
else
puts "#{email} does not match"
end

end
Note that this example provides only one solution. It does not have to be the best one.
emails = %w/ luke@gmail.com andy@yahoocom 23214sdj^as
f3444@gmail.com /
This is an array of emails. Only two of them are valid.
pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/
This is the pattern. The first ^ and the last $ characters are here to get an exact pattern match. No characters before and after the pattern are allowed. The email is divided into five parts. The first part is the local part. This is usually a name of a company, individual or a nickname. The [a-zA-Z0-9._-]+ lists all possible characters, we can use in the local part. They can be used one or more times. The second part is the literal @ character. The third part is the domain part. It is usually the domain name of the email provider. Like yahoo, gmail etc. [a-zA-Z0-9-]+ It is a character set providing all characters, than can be used in the domain name. The + quantifier makes use of one or more of these characters. The fourth part is the dot character. It is preceded by the escape character. (\.) This is because the dot character is a metacharacter and has a special meaning. By escaping it, we get a literal dot. Final part is the top level domain. The pattern is as follows: [a-zA-Z.]{2,5}Top level domains can have from 2 to 5 characters. Like sk, net, info, travel. There is also a dot character. This is because some top level domains have two parts. For example, co.uk.
$ ./email.rb
luke@gmail.com matches
andy@yahoocom does not match
23214sdj^as does not match
f3444@gmail.com matches
The regular expression marked two strings as valid email adresses.
In this chapter, we have covered regular expressions in Ruby.
Continue Reading

Ruby Object-oriented programming

In this part of the Ruby tutorial, we will continue talking about object-oriented programming in Ruby.
We start with attribute accessors. We will cover class constants, class methods and operator overloading. We will define polymorphism and will show how it is used in Ruby. We will also mention modules and exceptions.

Attribute accessors

All Ruby variables are private. It is possible to access them only via methods. These methods are often called setters and getters. Creating a setter and a getter method is a very common task. Therefore Ruby has convenient methods to create both types of methods. They are attr_reader, attr_writerand attr_accessor.
The attr_reader creates getter methods. The attr_writermethod creates setter methods and instance variables for this setters. The attr_accessor method creates both getter, setter methods and their instance variables.
#!/usr/bin/ruby

class Car

attr_reader :name, :price
attr_writer :name, :price

def to_s
"#{@name}: #{@price}"
end

end


c1 = Car.new
c2 = Car.new

c1.name = "Porsche"
c1.price = 23500

c2.name = "Volkswagen"
c2.price = 9500

puts "The #{c1.name} costs #{c1.price}"

p c1
p c2
We have a Car class. In the definition of the class, we use the attr_reader and attr_writer to create two getter and setter methods for the Car class.
attr_reader :name, :price
Here we create two instance methods named name and price. Note that the attr_reader takes symbols of methods as parameters.
attr_writer :name, :price  
The attr_writer creates two setter methods named name and price and two instance variables @name and @price.
c1.name = "Porsche"
c1.price = 23500
In this context, two setter methods are called to fill instance variables with some data.
puts "The #{c1.name} costs #{c1.price}"
Here two getter methods are called to get data from the instance variables of the c1 object.
$ ./arw.rb 
The Porsche costs 23500
Porsche: 23500
Volkswagen: 9500
Output of the example.

As we already stated above, the attr_accessor method creates both getter, setter methods and their instance variables.
#!/usr/bin/ruby

class Book
attr_accessor :title, :pages
end

b1 = Book.new
b1.title = "Hidden motives"
b1.pages = 255

p "The book #{b1.title} has #{b1.pages} pages"
We have a Book class in which the attr_accessorcreates two pairs of methods and two instance variables.
class Book
attr_accessor :title, :pages
end
The attr_accessor method that sets up title and pages methods and @title and @pages instance variables.
b1 = Book.new
b1.title = "Hidden motives"
b1.pages = 255
An object of a Book class is created. Two setter methods fill the instance variables of the object.
p "The book #{b1.title} has #{b1.pages} pages"
In this code line we use two getter methods to read the values of the instance variables.
$ ./accessor.rb
"The book Hidden motives has 255 pages"
Example output.

Class constants

Ruby enables to create class constants. These constants do not belong to a concrete object. They belong to the class. By convention, constants are written in uppercase letters.
#!/usr/bin/ruby

class MMath

PI = 3.141592
end


puts MMath::PI
We have a MMath class with a PI constant.
PI = 3.141592
We create a PI constant. Remember that constants in Ruby are not enforced.
puts MMath::PI
We access the PI constant using the :: operator.
$ ./classconstant.rb 
3.141592
Running the example.

The to_s method

Each object has a to_s method. It returns a string representation of the object. Note that when the puts method takes an object as a parameter, the to_s of the object is being called.
#!/usr/bin/ruby

class Being

def to_s
"This is Being class"
end
end

b = Being.new
puts b.to_s
puts b
We have a Being class in which we override the default implementation of the to_s method.
def to_s
"This is Being class"
end
Each class created inherits from the base Object. The to_s method belongs to this class. We overwrite the to_s method and create a new implementation. We provide a human-readable description of our object.
b = Being.new
puts b.to_s
puts b
We create a Being class and call the to_s method twice. The first time explicitly, the second time implicitly.
$ ./tostring.rb 
This is Being class
This is Being class
This is what we get, when we run the example.

Operator overloading

Operator overloading is a situation where different operators have different implementations depending on their arguments.
In Ruby there is only a slight distinction between an operator and a method.
#!/usr/bin/ruby

class Circle

attr_accessor :radius

def initialize r
@radius = r
end

def +(other)
Circle.new @radius + other.radius
end

def to_s
"Circle with radius: #{@radius}"
end
end


c1 = Circle.new 5
c2 = Circle.new 6
c3 = c1 + c2

p c3
In the example, we have a Circle class. We overload the + operator in the class. We use it to add two circle objects.
def +(other)
Circle.new @radius + other.radius
end
We define a method with a + name. The method adds the radiuses of two circle objects.
c1 = Circle.new 5
c2 = Circle.new 6
c3 = c1 + c2
We create two circle objects. In the third line, we add these two objects to create a new one.
$ ./operatoroverloading.rb
Circle with radius: 11
By adding two circle objects we have created a third one, which radius is 11.

Class methods

From a specific point of view, Ruby has two kinds of methods. Class methods and instance methods. Class methods are called on a class. They cannot be called on an instance of a class; on a created object.
Class methods cannot access instance variables.
#!/usr/bin/ruby

class Circle

def initialize x
@r = x
end

def self.info
"This is a Circle class"
end

def area
@r * @r * 3.141592
end

end


p Circle.info
c = Circle.new 3
p c.area
The above code example presents a Circle class. Apart from a constructor method, it has one class and one instance method.
def self.info
"This is a Circle class"
end
Methods that start with a self keyword are class methods.
def area
"Circle, radius: #{@r}"
end
Instance methods do not start with the self keyword.
p Circle.info
We call a class method. Note that we call the method on a class name.
c = Circle.new 3
p c.area
To call an instance method, we must first create an object. Instance methods are always called on an object. In our case, the c variable holds the object and we call the area method on the circle object. We utilize a dot operator.
$ ./classmethods.rb
"This is a Circle class"
28.274328
Output of the code example describing class methods in Ruby.

There are three ways to create a class method in Ruby.
#!/usr/bin/ruby

class Wood

def self.info
"This is a Wood class"
end
end

class Brick

class << self
def info
"This is a Brick class"
end
end
end

class Rock

end

def Rock.info
"This is a Rock class"
end


p Wood.info
p Brick.info
p Rock.info
The example has three classes. Each of them has one class method.
def self.info
"This is a Wood class"
end
Class methods may start with a self keyword.
class << self
def info
"This is a Brick class"
end
end
Another way is to put a method definition after the class << self construct.
def Rock.info
"This is a Rock class"
end
This is the third way to define a class method in Ruby.
$ ./classmethods2.rb
"This is a Wood class"
"This is a Brick class"
"This is a Rock class"
We see the output of calling all three class methods on a Wood, Brick and Rock classes.

Three ways to create an instance method

Ruby has three basic ways to create instance methods. Instance methods belong to an instance of an object. They are called on an object using a dot operator.
#!/usr/bin/ruby

class Wood

def info
"This is a wood object"
end
end

wood = Wood.new
p wood.info

class Brick

attr_accessor :info
end

brick = Brick.new
brick.info = "This is a brick object"
p brick.info

class Rock

end

rock = Rock.new

def rock.info
"This is a rock object"
end

p rock.info
In the example we create three instance objects from a Wood, a Brick and a Rock class. Each object has one instance method defined.
class Wood

def info
"This is a wood object"
end
end

wood = Wood.new
p wood.info
This is probably the most common way to define and call an instance method. The info method is defined inside the Wood class. Later, the object is created and we call the info method on the object instance.
class Brick

attr_accessor :info
end

brick = Brick.new
brick.info = "This is a brick object"
p brick.info
Another way is to create a method using the attribute accessors. This is a convenient way which saves some typing for the programmer. The attr_accessor creates two methods, the getter and the setter method and it also creates an instance variable which stores the data. The brick object is created and the data is stored in the @info variable using the info setter method. Finally, the message is read by the info getter method.
class Rock

end

rock = Rock.new

def rock.info
"This is a rock object"
end

p rock.info
In the third way we create an empty Rock class. The object is instantiated. Later, a method is dynamically created and placed into the object.
$ ./threeways.rb
"This is a wood object"
"This is a brick object"
"This is a rock object"
Example output.

Polymorphism

The polymorphism is the process of using an operator or function in different ways for different data input. In practical terms, polymorphism means that if class B inherits from class A, it doesn't have to inherit everything about class A; it can do some of the things that class A does differently. (Wikipedia)
In general, polymorphism is the ability to appear in different forms. Technically, it is the ability to redefine methods for derived classes. Polymorphism is concerned with the application of specific implementations to an interface or a more generic base class.
Note that there is some difference in the definition of the polymorphism in statically typed languages like C++, Java or C# and dynamically typed languages like Python or Ruby. In statically typed languages it is important when the compilers determine the method definition. At compile time or at run time. In dynamically typed languages we concentrate on the fact, that methods with the same name do different things.
#!/usr/bin/ruby

class Animal

def make_noise
"Some noise"
end

def sleep
puts "#{self.class.name} is sleeping."
end

end

class Dog < Animal

def make_noise
'Woof!'
end

end

class Cat < Animal

def make_noise
'Meow!'
end
end

[Animal.new, Dog.new, Cat.new].each do |animal|
puts animal.make_noise
animal.sleep
end
We have a simple inheritance hierarchy. There is an Animal base class and two descendants, a Cat and a Dog. Each of these three classes has its own implementation of the make_noise method. The implementation of the method of the descendants replaces the definition of a method in the Animal class.
class Dog < Animal

def make_noise
'Woof!'
end

end
The implementation of the make_noise method in the Dog class replaces the implementation of the make_noise of the Animal class.
[Animal.new, Dog.new, Cat.new].each do |animal|
puts animal.make_noise
animal.sleep
end
We create an instance of ech of the classes. We call make_noise and sleep methods on the objects.
$ ./polymorhism.rb
Some noise
Animal is sleeping.
Woof!
Dog is sleeping.
Meow!
Cat is sleeping.
Output of the polymorhism.rb script.

Modules

A Ruby Module is a collection of methods, classes and constants. Modules are similar to classes with a few differences. Modules cannot have instances. They have no subclasses.
Modules serve two basic purposes. They are used to organize code. Classes, methods and constants which have something in common can be put into separate modules. This also prevents name clashes, because all objects are unique by their module. In this context, Ruby modules are similar to C# namespaces and Java packages.
The second purpose of a module is to create mixins. A mixin is a Ruby facility to create multiple inheritance. If a class inherits functionality from more than one class, we speak of multiple inheritance.
#!/usr/bin/ruby

puts Math::PI
puts Math.sin 2
Ruby has a built-in Math module. It has multiple methods and a constant. We access the PI constant by using the :: operator. Methods are accessed by a dot operator as in classes.
#!/usr/bin/ruby

include Math

puts PI
puts sin 2
If we include a module in our script, we can refer to the Math objects directly, omitting the Math name. Modules are added to a script using the include keyword.
$ ./modules.rb
3.141592653589793
0.9092974268256817
Output of the program.

In the following example, we show how modules can be used to organize code.
#!/usr/bin/ruby

module Forest

class Rock ; end
class Tree ; end
class Animal ; end

end

module Town

class Pool ; end
class Cinema ; end
class Square ; end
class Animal ; end

end


p Forest::Tree.new
p Forest::Rock.new
p Town::Cinema.new

p Forest::Animal.new
p Town::Animal.new
Ruby code can be grouped semantically. Rocks, trees belong to a forest. And pools, cinemas, squares belong to a town. By using modules our code has some order. Plus there is another thing. Animals can be in a forest and in a town too. In a single script, we cannot define two animal classes. They would clash. Putting them in different modules we solve the issue.
p Forest::Tree.new
p Forest::Rock.new
p Town::Cinema.new
We are creating objects that belong to a forest and to a town. To access an object in a module, we use the :: operator.
p Forest::Animal.new
p Town::Animal.new
Two different animal objects are created. The Ruby interpreter can tell between them. It identifies them by their module name.
$ ./modules3.rb
#<Forest::Tree:0x97f35ec>
#<Forest::Rock:0x97f35b0>
#<Town::Cinema:0x97f3588>
#<Forest::Animal:0x97f3560>
#<Town::Animal:0x97f3538>


The final code example of this section will demonstrate multiple inheritance using Ruby modules. In this context the modules are called mixins.
#!/usr/bin/ruby

module Device
def switch_on ; puts "on" end
def switch_off ; puts "off" end
end

module Volume
def volume_up ; puts "volume up" end
def vodule_down ; puts "volume down" end
end

module Pluggable
def plug_in ; puts "plug in" end
def plug_out ; puts "plug out" end
end

class CellPhone
include Device, Volume, Pluggable

def ring
puts "ringing"
end
end

cph = CellPhone.new
cph.switch_on
cph.volume_up
cph.ring
We have three modules and one class. The modules represent some functionality. A device can be swiched on and off. Many objects can share this functionality. Televisions, mobile phones, computers or refrigerators. Rather than creating this ability to be swiched on/off for each object class, we separate it in one module, which can be included in each object if necessary. This way the code is better organized and more compact.
module Volume
def volume_up ; puts "volume up" end
def vodule_down ; puts "volume down" end
end
A Volume module organizes methods, than are responsible for controlling the volume level. If a device needs these methods, it simply includes the module to its class.
class CellPhone
include Device, Volume, Pluggable

def ring
puts "ringing"
end
end

A cell phone adds all three modules with the include method. The methods of the modules are mixed in the CellPhone class. And are available for the instances of the class. The CellPhone class has also its own ring method that is specific to it.
cph = CellPhone.new
cph.switch_on
cph.volume_up
cph.ring
A CellPhone object is created and we call three methods upon the object.
$ ./mixins.rb
on
volume up
ringing
Running the example.

Exceptions

Exceptions are designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution. Exceptions are raised, thrown or initiated.
During the execution of our application, many things might go wrong. A disk might get full and we cannot save our file. An Internet connection might go down and our application tries to connect to a site. All these might result in a crash of our application. To prevent happening this, we must cope with all possible errors that might occur. For this, we can use the exception handling.
Exceptions are objects. They are descendants of a built-in Exceptionclass. Exception objects carry information about the exception. Its type (the exception’s class name), an optional descriptive string, and optional traceback information. Programs may subclass Exception, or more often StandardError to provide custom classes and add additional information.
#!/usr/bin/ruby

x = 35
y = 0

begin
z = x / y
puts z
rescue => e
puts e
p e
end
In the above program, we intentionally divide a number by zero. This leads to an error.
begin
z = x / y
puts z
Statements that are error prone are placed after the begin keyword.
rescue => e
puts e
p e
end
In the code following the rescue keyword, we deal with an exception. In this case, we print the error message to the console. The e is an exception object that is created when the error occurs.
$ ./zerodivision.rb
divided by 0
#<ZeroDivisionError: divided by 0>
In the output of the example, we see the message of the exception. The last line shows the exception object called ZeroDivisionError.

A programmer may raise exceptions himself using the raise keyword.
#!/usr/bin/ruby

age = 17

begin
if age < 18
raise "Person is minor"
end

puts "Entry allowed"
rescue => e
puts e
p e
exit 1
end
The entrance to a club is not allowed for people younger than 18 years. We simulate this situation in our Ruby script.
begin
if age < 18
raise "Person is minor"
end

puts "Entry allowed"
If the person is minor, an exception is raised. If the raise keyword does not have a specific exception as a parameter, a RuntimeError exception is raised setting its message to the given string. The code does not reach the puts "Entry allowed" line. The execution of the code is interrupted and it continues at the rescue block.
rescue => e
puts e
p e
exit 1
end
In the rescue block, we print the error message and the string representation of the RuntimeError object. We also call the exit method to inform the environment that the execution of the script ended in error.
$ ./raise_exception.rb
Person is minor
#<RuntimeError: Person is minor>
$ echo $?
1
The person was minor and he or she was not allowed to enter the club. The bash $? variable is set to the exit error of the script.

With the Ruby ensure clause we create a block of code that is always executed. Whether there is an exception or not.
#!/usr/bin/ruby

begin
f = File.open("stones", "r")

while line = f.gets do
puts line
end

rescue => e
puts e
p e
ensure
f.close if f
end
In the code example, we try to open and read the stones file. I/O operations are error prone. We could easily have an exception.
ensure
f.close if f
end
In the ensure block we close the file handler. We check if the handler exists because it might not have been created. Allocated resources are often placed in the ensure block.

We can create our own custom exceptions if we want. Custom exceptions in Ruby should inherit from the StandardError class.
#!/usr/bin/ruby

class BigValueError < StandardError ; end

LIMIT = 333
x = 3_432_453

begin

if x > LIMIT
raise BigValueError, "Exceeded the maximum value"
end

puts "Script continues"

rescue => e
puts e
p e
exit 1
end
Let's say, we have a situation in which we cannot deal with big numbers.
class BigValueError < StandardError ; end
We have a BigValueError class. This class derives from the built-in StandardError class.
LIMIT = 333
Numbers which exceed this constant are considered to be "big" by our program.
if x > LIMIT
raise BigValueError, "Exceeded the maximum value"
end
If the value is bigger than the limit, we throw our custom exception. We give the exception a message "Exceeded the maximum value".
$ ./custom_exception.rb
Exceeded the maximum value
#<BigValueError: Exceeded the maximum value>
Running the program.
In this chapter we finished talking about object-oriented programming in Ruby language.
Continue Reading

Object-oriented programming in Ruby

In this part of the Ruby tutorial, we will talk about object-oriented programming in Ruby.
There are three widely used programming paradigms there. Procedural programming, functional programming and object-oriented programming. Ruby is an object-oriented language. It has some functional and procedural features too.
Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. (Wikipedia)
There are some basic programming concepts in OOP:
  • Abstraction
  • Polymorphism
  • Encapsulation
  • Inheritance
The abstraction is simplifying complex reality by modeling classes appropriate to the problem. The polymorphism is the process of using an operator or function in different ways for different data input. The encapsulation hides the implementation details of a class from other objects. The inheritance is a way to form new classes using classes that have already been defined.

Objects

Objects are basic building blocks of a Ruby OOP program. An object is a combination of data and methods. In a OOP program, we create objects. These objects communicate together through methods. Each object can receive messages, send messages and process data.
There are two steps in creating an object. First, we define a class. A class is a template for an object. It is a blueprint, which describes the state and behavior that the objects of the class all share. A class can be used to create many objects. Objects created at runtime from a class are called instances of that particular class.
#!/usr/bin/ruby

class Being

end

b = Being.new
puts b
In our first example, we create a simple object.
class Being

end
This is a simple class definition. The body of the template is empty. It does not have any data or methods.
b = Being.new
We create a new instance of the Being class. For this we have the new method. The b variable stores the newly created object.
puts b
We print the object to the console to get some basic description of the object. What does it mean, to print an object? When we print an object, we in fact call its to_s method. But we have not defined any method yet. It is because every object created inherits from the base Object. It has some elementary functionality, which is shared among all objects created. One of this is the to_s method.
$ ./simple.rb
#<Being:0x9f3c290>
We get the object class name.

The constructor

A constructor is a special kind of a method. It is automatically called, when the object is created. Constructors do not return values. The purpose of the constructor is to initiate the state of an object. The constructor in Ruby is called initialize. Constructors do not return any values.
Constructors cannot be inherited. The constructor of a parent object is called with a super method. They are called in the order of inheritance.
#!/usr/bin/ruby

class Being

def initialize
puts "Being is created"
end

end

Being.new
We have a Being class.
class Being

def initialize
puts "Being is created"
end

end
The Being class has a constructor method called initialize. It prints a message to the console. The definition of a Ruby method is placed between the def and end keywords.
Being.new
An instance of the Being class is created. At the moment of the object creation, the constructor method is called.
$ ./constructor.rb
Being is created
This is the output of the program.

Object attributes is the data bundled in an instance of a class. The object attributes are called instance variables or member fields. An instance variable is a variable defined in a class, for which each object in the class has a separate copy.
In the next example, we initiate data members of the class. Initiation of variables is a typical job for constructors.
#!/usr/bin/ruby

class Person

def initialize name
@name = name
end

def get_name
@name
end

end

p1 = Person.new "Jane"
p2 = Person.new "Beky"

puts p1.get_name
puts p2.get_name
In the above Ruby code, we have a Person class with one member field.
class Person

def initialize name
@name = name
end
In the constructor of the Person class, we set a member field to a value name. The name parameter is passed to the constructor at creation. A constructor is a method called initializethat is being called at the creation of an instance object. The @name is an instance variable. Instance variables start with @ character in Ruby.
def get_name
@name
end
The get_name method returns the member field. In Ruby member fields are accessible only via methods.
p1 = Person.new "Jane"
p2 = Person.new "Beky"
We create two objects of a Person class. A string parameter is passed to each object constructor. The names are stored inside instance variables that are unique to each object.
puts p1.get_name
puts p2.get_name
We print the member fields by calling the get_name on each of the objects.
$ ./person.rb
Jane
Beky
We see the output of the program. Each instance of the Person class has its own name member field.

We can create an object without calling the constructor. Ruby has a special allocate method for this. The allocate method allocates space for a new object of a class and does not call initialize on the new instance.
#!/usr/bin/ruby

class Being

def initialize
puts "Being created"
end
end


b1 = Being.new
b2 = Being.allocate
puts b2
In the example, we create two objects. The first object using the new method, the second object using the allocate method.
b1 = Being.new
Here we create an instance of the object with the new keyword. The constructor method initialize is called and the message is printed to the console.
b2 = Being.allocate
puts b2
In case of the allocate method, the constructor is not called. We call the to_s method with the puts keyword to show, that the object was created.
$ ./allocate.rb
Being created
#<Being:0x8ea0044>
Output of the program.

Constructor overloading

Constructor overloading is the ability to have multiple types of constructors in a class. This way we can create an object with different number or different types of parameters.
Ruby has no constructor overloading that we know from other programming languages. This behaviour can be simulated to some extent with default parameter values in Ruby.
#!/usr/bin/ruby


class Person

def initialize name="unknown", age=0
@name = name
@age = age
end

def to_s
"Name: #{@name}, Age: #{@age}"
end

end

p1 = Person.new
p2 = Person.new "unknown", 17
p3 = Person.new "Becky", 19
p4 = Person.new "Robert"

p p1, p2, p3, p4
This example shows how we could simulate constructor overloading on a Person class that has two member fields. If we do not specify the name of the person, we have "unknown" string instead. For unspecified age we have 0.
def initialize name="unknown", age=0
@name = name
@age = age
end
The constructor takes two parameters. They have a default value. The default value is used, if we do not specify our own values at the object creation. Note that the order of parameters must be kept. First comes the name, then the age.
p1 = Person.new
p2 = Person.new "unknown", 17
p3 = Person.new "Becky", 19
p4 = Person.new "Robert"

p p1, p2, p3, p4
We create four objects. The constructors take different number of parameters.
$ ./consover.rb
Name: unknown, Age: 0
Name: unknown, Age: 17
Name: Becky, Age: 19
Name: Robert, Age: 0
Output of the example.

Methods

Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods are essential in encapsulation concept of the OOP paradigm. For example, we might have a connect method in our AccessDatabase class. We need not to be informed, how exactly the method connects to the database. We only have to know, that it is used to connect to a database. This is essential in dividing responsibilities in programming. Especially in large applications.
In Ruby, data is accessible only via methods.
#!/usr/bin/ruby

class Person

def initialize name
@name = name
end

def get_name
@name
end

end

per = Person.new "Jane"

puts per.get_name
puts per.send :get_name
The example shows two basic ways to call a method.
puts per.get_name
The common way is to use a dot operator on an object followed by a method name.
puts per.send :get_name
The alternative is to use a built-in send method. It takes a symbol of the method to be called as a parameter.

Methods typically perform some action on the data of the object.
#!/usr/bin/ruby

class Circle

@@PI = 3.141592

def initialize
@radius = 0
end

def set_radius radius
@radius = radius
end

def area
@radius * @radius * @@PI
end

end


c = Circle.new
c.set_radius 5
puts c.area
In the code example, we have a Circle class. We define two methods.
@@PI = 3.141592
We have defined a @@PI variable in our Circle class. It is a class variable. Class variables start with @@ sigils in Ruby. Class variables belong to a class, not to an object. Each object has access to its class variables. We use the @@PI to compute the area of the circle.
def initialize
@radius = 0
end
We have one member field. It is the radius of the circle. If we want to modify this variable from the outside, we must use the publicly available set_radius method. The data is protected.
def set_radius radius
@radius = radius
end
This is the set_radius method. It gives the @radius instance variable a new value.
def area
@radius * @radius * @@PI
end
The area method returns the area of a circle. This is a typical task for a method. It works with data and produces some value for us.
c = Circle.new
c.set_radius 5
puts c.area
We create an instance of the Circle class. And set its radius by calling the set_radius method on the object of the circle. We use the dot operator to call the method.
$ ./circle.rb
78.5398
Running the example.

Access modifiers

Access modifiers set the visibility of methods and member fields. Ruby has three access modifiers: public, protectedand private. In Ruby, all data members are private. Access modifiers can be used only on methods. Ruby methods are public, unless we say otherwise.
The public methods can be accessed from inside the definition of the class as well as from the outside of the class. The difference between the protected and the private methods is subtle. They both cannot be accessed outside the definition of the class. They can be accessed only within the class itself and by inherited or parent classes.
Note that unlike in other object-oriented programming languages, inheritance does not play role in Ruby access modifiers. Only two things are important. First, if we call the method inside or outside the class definition. Second, if we use or do not use the self keyword which points to the current receiver.
Access modifiers protect data against accidental modifications. They make the programs more robust. The implementation of some methods is subject to change. These methods are good candidates for being private. The interface that is made public to the users should only change when really necessary. Over the years users are accustomed to using specific methods and breaking backward compatibility is generally frowned upon.
#!/usr/bin/ruby

class Some

def method1
puts "public method1 called"
end

public

def method2
puts "public method2 called"
end

def method3
puts "public method3 called"
method1
self.method1
end
end

s = Some.new
s.method1
s.method2
s.method3
The example explains the usage of public Ruby methods.
def method1
puts "public method1 called"
end
The method1 is public, even if we did not specify the public access modifier. It is because methods are public by default, if not specified otherwise.
public

def method2
puts "public method2 called"
end

...
Methods following the public keyword are public.
def method3
puts "public method3 called"
method1
self.method1
end
From inside the public method3, we call other public method. With and without the self keyword.
s = Some.new
s.method1
s.method2
s.method3
Public methods are the only methods that can be called outside the definition of a class as shown here.
$ ./public_methods.rb
public method1 called
public method2 called
public method3 called
public method1 called
public method1 called
Running the example.

The next example looks at private methods.
#!/usr/bin/ruby


class Some

def initialize
method1
# self.method1
end

private

def method1
puts "private method1 called"
end

end


s = Some.new
# s.method1
Private methods are tightest methods in Ruby. They can be called only inside a class definition and without the self keyword.
def initialize
method1
# self.method1
end
In the constructor of the method, we call the private method1. Calling the method with the self is commented. Private methods cannot be specified with a receiver.
private

def method1
puts "private method1 called"
end
Methods following the private keyword are private in Ruby.
s = Some.new
# s.method1
We create an instance of the Some class. Calling the method outside the class definition is prohibited. If we uncomment the line, the Ruby interpreter gives an error.
$ ./private_methods.rb
private method called
Output of the example code.

Finally, we will work with protected methods. The distinction between the protected and the private methods in Ruby is subtle. Protected methods are like private. There is only one small difference. They can be called with the selfkeyword specified.
#!/usr/bin/ruby

class Some

def initialize
method1
self.method1
end

protected

def method1
puts "protected method1 called"
end

end


s = Some.new
# s.method1
The above example shows protected method in usage.
def initialize
method1
self.method1
end
Protected methods can be called with and without the self keyword.
protected

def method1
puts "protected method1 called"
end
Protected methods are preceded by the protected keyword.
s = Some.new
# s.method1
Protected methods cannot be called outside the class definition. Uncommenting the line would lead to an error.

Inheritance

The inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called base classes. Important benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) override or extend the functionality of base classes (ancestors).
#!/usr/bin/ruby

class Being

def initialize
puts "Being class created"
end
end

class Human < Being

def initialize
super
puts "Human class created"
end
end

Being.new
Human.new
In this program, we have two classes. A base Being class and a derived Human class. The derived class inherits from the base class.
class Human < Being
In Ruby, we use the < operator to create inheritance relations. The Human class inherits from the Being class.
def initialize
super
puts "Human class created"
end
The super method calls the constructor of the parent class.
Being.new
Human.new
We instantiate the Being and the Human class.
$ ./inheritance.rb 
Being class created
Being class created
Human class created
First the Being class is created. The derived Human class also calls the costructor of its parent.

An Object may be involved in comlicated relationships. A single object can have multiple ancestors. Ruby has a method ancestors which gives a list of ancestors for a specific class.
Each Ruby object is automatically a descendant of Object, BasicObject classes and Kernel Module. They are built-in the core of the Ruby language.
#!/usr/bin/ruby


class Being
end

class Living < Being
end

class Mammal < Living
end

class Human < Mammal
end


p Human.ancestors
We have four classes in this example. A Human is a Mammal a Living and a Being.
p Human.ancestors
We print the ancestors of a Human class.
$ ./ancestors.rb 
[Human, Mammal, Living, Being, Object, Kernel, BasicObject]
A Human class has three custom and three built-in ancestors.

A more complex example follows.
#!/usr/bin/ruby

class Being

@@count = 0

def initialize
@@count += 1
puts "Being class created"
end

def show_count
"There are #{@@count} beings"
end

end

class Human < Being

def initialize
super
puts "Human is created"
end
end

class Animal < Being

def initialize
super
puts "Animal is created"
end
end

class Dog < Animal

def initialize
super
puts "Dog is created"
end
end

Human.new
d = Dog.new
puts d.show_count
We have four classes. The inheritance hierarchy is more complicated. The Human and the Animal classes inherit from the Being class. And the Dog class inherits directly from the Animal class and further from the Being class. We also use a class variable to count the number of beings created.
@@count = 0
We define a class variable. A class variable begins with @@ sigils and it belongs to the class, not to the instance of the class. We use it to count the number of beins created.
def initialize
@@count += 1
puts "Being class created"
end
Each time the Being class is instantiated, we increase the @@count variable by one. This way we keep track of the number of instances created.
class Animal < Being
...

class Dog < Animal
...
The Animal inherits from the Being and the Dog inherits from the Animal. Further, the Dog inherits from the Being as well.
Human.new
d = Dog.new
puts d.show_count
We create instances from the Human and from the Dog classes. We call the show_count method on the Dog object. The Dog class has no such method; the grandparent's (Being) method is called then.
$ ./inheritance2.rb
Being class created
Human is created
Being class created
Animal is created
Dog is created
There are 2 beings
The Human object calls two constructors. The Dog object calls three constructors. There are two Beings instantiated.

Inheritance does not play role in the visibility of methods and data members. This is a notable difference from many common object-oriented programming languages.
In C# or Java, private data members and methods are not inherited. Only public and protected. In contrast to this, private data members and methods are inherited in Ruby as well. The visibility of data members and methods is not affected by inheritance in Ruby.
#!/usr/bin/ruby

class Base

def initialize
@name = "Base"
end

private

def private_method
puts "private method called"
end

protected

def protected_method
puts "protected_method called"
end

public

def get_name
return @name
end
end


class Derived < Base

def public_method
private_method
protected_method
end
end

d = Derived.new
d.public_method
puts d.get_name
In the example we have two classes. The Derived class inherits from the Base class. It inherits all three methods and one data field.
def public_method
private_method
protected_method
end
In the public_method of the Derived class we call one private and one protected method. They were defined in the parent class.
d = Derived.new
d.public_method
puts d.get_name
We create an instance of the Derived class. We call the public_method. And call the get_name method, which returns the private @name variable. Remember that all instance variables are private in Ruby. The get_name method returns the variable regardless of the fact, that it is private and defined in the parent class.
$ ./inheritance3.rb
private method called
protected_method called
Base
The output of the example confirms that in Ruby language, public, protected, private methods and private member fields are inherited by child objects from their parents.

The super method

The super method calls a method of the same name in the parent's class. If the method has no arguments it automatically passes all its arguments. If we write super() no arguments are passed to parent's method.
#!/usr/bin/ruby

class Base

def show x=0, y=0
p "Base class, x: #{x}, y: #{y}"
end
end

class Derived < Base

def show x, y
super
super x
super x, y
super()
end
end


d = Derived.new
d.show 3, 3
In the example, we have two classes in a hierarchy. They both have a show method. The show method in the Derived class calls the show method in the Base class using the super method.
def show x, y
super
super x
super x, y
super()
end
The super method without any arguments calls the parent's show method with the arguments that were passed to the show method of the Derived class. In our case x=3, y=3. The super() method passes no arguments to the parent's show method.
$ ./super.rb
"Base class, x: 3, y: 3"
"Base class, x: 3, y: 0"
"Base class, x: 3, y: 3"
"Base class, x: 0, y: 0"
Output of the example.
This was the first part of the description of OOP in Ruby.
Continue Reading