Inheritance

Inherited classes allow for similar code to be re-used, this saves on code space and also development/testing time. Inherited classes basically have access to the internals of the “super” inherited class.

To create a inherited class
class sibling < superclass

And the sibling class can then call any methods etc within the superclass. The code example explains in code 😉

# base "Books" class
class Books
   # this is called within the .new class call
   def initialize(name, author, year)
       @name = name;
       @author = author;
       @year = year;
   end
 
   def to_s
          # return the to_s (to_string)
          "Books - Name #{@name} - Author #{@author} - Year #{@year}"
   end          
end
 
# this class is Inherited from the "Books" class
class BookToCD < Books
    def initialize(name, author, year, cdID)
           # use the "Books" class initlialize to setup the local variables within the super/inherited class
           super(name, author, year)
           #setup the local variables
           @cdID = cdID
    end
 
    def to_s
           # get the result from the super class
           result = super.to_s
           # return the result from the super class + the local cdID variable
           return result + " - CDID #{@cdID}" 
    end
end
# create a book
book = Books.new("Programming in Ruby", "Ruby Team", 2006)
# inspect outputs the internel structure of the class
puts book.inspect
puts book.to_s
 
booktocd = BookToCD.new("CD read of programming in Ruby", "Ruby Team",2006, 1)
# the inspect shows that the new class has a different memory address
puts booktocd.inspect
puts booktocd.to_s

Once executed on the command line the result is

#<Books:0x2777070 @year=2006, @name="Programming in Ruby", @author="Ruby Team">
Books - Name Programming in Ruby - Author Ruby Team - Year 2006
#<BookToCD:0x2776f38 @year=2006, @name="CD read of programming in Ruby", @cdID=1, @author="Ruby Team">
Books - Name CD read of programming in Ruby - Author Ruby Team - Year 2006 - CDID 1

As you can see the inspect method is showing that the memory block of the book and also booktocd are not the same even though they are sharing the same internals, this is Object Orientated.

Methods, Arrays, Hash

First part is the method and the second is the array and hash variables.

The manor in which Ruby returns values from a method is either by the return keyword or by the last executed line of code, thus if the result for the return of the method is the last line then there is no need to use the return keyword, but of course if the returnable value is calculated within the middle of the method and the rest is to clean up the method then use the return keyword.

# this is a basic method
def saySomething(name)
       result = "hi there #{name}"
       return result
end
 
# but Ruby will return the last evaluated line, thus this method
# is the same as the above one.
def saySomething2(name)
       "hi there #{name}"
end
 
# the two methods that are the same in there results
puts saySomething("Ian")
puts saySomething2("Ian Porter")

Below is how Ruby uses the array structure and also the hash structure, an array is defined within the [ ] brackets and the start of the array is 0, but within a hash since there is no start to the hash keys, then there is an hash key and then the values associated with that key. The hash structure is defined within { } brackets.

# this is a array
a = ['Gentoo Linux','is','great']
 
#this is a hash, an hash is a key -> value
has = { 'Gentoo' => 'Gentoo Linux',
       'RH' => 'Red Hat Linux'}       # hash
 
puts a[0]       # print the first element of the array
puts a              # print the arary
 
puts "The Key value of RH within the hash"
puts has['RH']       # print the value assoicated with the key RH
puts "The hash in full"
puts has

Once executed from the console, the output is

hi there Ian
hi there Ian Porter

for the first method demonstrating that the result value is the same

Gentoo Linux
Gentoo Linux
is
great
The Key value of RH within the hash
Red Hat Linux
The hash in full
RHRed Hat LinuxGentooGentoo Linux

Which shows the results of the program, this shows that the two methods return in the same manor and also an array is broken into separate blocks, but a hash has a continuous memory block in nature.

Class And Modules

A Ruby class is very similar to the other programming languages class structures. They allow for code to be created within a single object that can be reused etc, the code can have its own separate block of variables/methods for that instance of the required task. It is able to be inherited and extended which is different to a module which only allows for the created module to have methods and constant variables.

module SillyModule

Method – Add Two numbers

This tutorial uses the same code as Add two numbers but includes a function/method to add two numbers together and return a value. The addtwo function has two parameters that are returned back added together. I have called them a and b, so that they are different names to the variables within the main method.

The source code

# define a function called addtwo with two parameters
def addtwo(a, b) 
       a + b; # return a + b
end
 
print "Please enter number 1 : ";
# get the input from the console, 
val1 = gets;
print "Please enter number 2 : ";
val2 = gets;
# convert the string console inputs to_i (to_integers) and add together
print "Answer : " , (val1.to_i + val2.to_i), "\n";

save as addtwonumbers_function.rb, this program will function the same as the previous tutorial apart from the inner working will call the method. The method programming allows for one method to be called multiple times, e.g. Within the example above there could be a method that was 5 lines in length and instead of writing the same 5 lines each time, you just write a method that is called.

Add two numbers

This tutorial will demonstrate how to read from the input console (console line) to answer the prompts. The prompts will need to be a integer value to add the two inputs together.

The gets function is able to get a string from the console input, with the string inputted this allows the string function .to_i (to_integer) conversion for the answer to add up to integer values.

The code

print "Please enter number 1 : ";
# get the input from the console, 
val1 = gets;
print "Please enter number 2 : ";
val2 = gets;
# convert the string console inputs to_i (to_integers) and add together
print "Answer : " , (val1.to_i + val2.to_i), "\n";

save that as addtwonumbers.rb.

To run ruby addtwonumbers.rb, and the output would be similar to

Please enter value 1 : 30
Please enter value 2: 23
Answer = 53

Read/Write files

This is a tutorial on how to open and write files with Ruby, of course there is always different ways to accomplish the same task within programming languages.

The objects e.g. File, have different functions associated with them. The File.new creates a new file, the IO (InputOutput) object is an allows for different Input output tasks, which in this case to read each line of the input file (countrys.txt) and assign the value to ‘line’. The puts prints out what has been read in, and the syswrite, which was created from the File.net outputs to the output file.

NOTE: the { } are the begin and end of a code structure, e.g. While begin; do something; end;

This is the code

OutFile = File.new("sqlrubycountry.txt","w");
 
IO.foreach("countrys.txt") { |line|
        puts line
        OutFile.syswrite("insert into country(place) values (\"#{line.strip}\");\n");
}
 
OutFile.close;

if you save that as rubyreadfile.rb and also create a countrys.txt file with what ever text you like, e.g.
United Kingdom
France
Germany
United States etc.

The output of the program (ruby rubyreadfile.rb) will display each line that is read from the input file and the output file will have some other text in it, for demonstrating purposes, have done some sql code.

Hello world Ruby style

To get Ruby . Ruby is a development environment that is similar to other Object Oriented (OO) languages, but it is designed to be developed in quickly with a stable environment. Ruby can be used to create GUI’s to websites very quickly.

This first source code is the very basic Hello word!.

If you save this code

puts "Hello World";

as rubyhelloworld.rb

The file extension rb just stands for Ruby. To run the code from the command line, where you have saved the file above

ruby rubyhelloworld.rb

and the output will be

Hello World

Hope that helps people.