Ruby Tutorial Part 04 Writing, Exceptions and Reflection

Repository

https://github.com/ruby/ruby 

What Will I Learn?

  • You will learn the output ( writing ).
  • You will learn Exceptions.
  • You will learn Reflection.

Requirements

  • You need to have Ruby installed on your computer

Difficulty

  • Basic

Tutorial Contents

1- Writing

In order to write or print anything on the screen the programming languages offer " built in " functions that accept the string and print it on the screen.

Java for example uses " print and println " , C uses " printf " ..etc , for Ruby language there is four functions :

syswrite, puts, putc and each_byte.

Syswrite Function

This function used to write a string in a file for example or on the screen, it accepts the string as parameter.

Puts Function

The puts function similar to the syswrite function, it accepts a string as parameter and print it.

Putc Function

The puts is put string and putc is put character, the difference between " puts and putc " that the putc accepts a character as parameter not string.

Each_Byte Function

The each_byte method means each character, used to do an iteration to print all the content of a file for example byte by byte or character by character at place of using loop and " putc " function.

#Create a file Object in Write mode, if it exists it'll be overwritten 
fileObj=File.new('E:\Ruby26\bin\utopian.txt', 'w') 
#Print a string to the file by using syswrite method of the file Object 
fileObj.syswrite("Hello from Ruby IO!") 
#Close the file object!
fileObj.close
Reading 
fileObj=File.new('E:\Ruby26\bin\utopian.txt', 'r') 
#Read it 
fileSrc=fileObj.gets 
#print it 
puts fileSrc 
fileObj.close() #Close it. 

Firstly "fileObj" is a file object opened in write mode, using the syswrite function the string passed as parameter to this function will be added to the opened file, and after each opening of the file is closed again.

Secondly "fileObj" is a file object opened in read mode, the reason to open the file with this mode just to test if the file contains the string that has been added or not, for that the function " puts " will be used to print the result, then the file will be closed.

#Create a file Object in read mode 
fileObj=File.new('E:\Ruby26\bin\utopian.txt', 'r') 
#Read it 
fileObj.each_byte {|char|
  putc char 
} 
#Close it 
fileObj.close() 

To use the method " each_byte ", there should be a file with content to be reading character by character, and inside the function " putc " used to print them, after the process finished the file should be closed.

Exceptions

The debugging is a process to test the software or the application before providing to the client, so if an error occurs the client will contact the programmer, and he will solve it and so on.

The exceptions is the great way to solve all the problems before, it will handle the error and return an understandable error message to the client.

For example a calculator program, the client enters 5/0 and the division by 0 is an error there is no result for this operation, it will return this result 

divided by 0 (ZeroDivisionError)

What's the solution ?

2- Begin, Rescue, Ensure and End

The " begin rescue, ensure and end " is the same like " try and catch " in Java and other programming languages, in the begin block there is the normal code, if there is an error the " rescue " block will be executed, so you can use anything in your " rescue " block, and finally as the begin there is the end.

begin          
#your normal code goes here.           
#error! 
rescue           
#rescue 
ensure          
#always happen! 
end 
begin  
puts 1/0
rescue ZeroDivisionError  
puts "You are dividing by zero"  
exit(1) 
#terminate
end 

For the division by 0 example, the " begin " block contains the normal code " puts 1/0 ", if there is an error the " rescue " will be executed, so inside the " rescue " block a message will be printed to the user " You are dividing by zero ", finally the " end " to terminate the code.

Because the error is " ZeroDivisionError ", the result will be " You are dividing by zero ".

The exit method can be used in the " ensure " block, so the ensure used to connect or exit or something like that.

begin  
puts 1/0 
rescue ZeroDivisionError
  puts "You are dividing by zero"  
ensure  
exit(1) 
#terminate 
end

At place of using " exit " in " rescue " we use it in the " ensure " block.

3- Reflection

Is the ability to handle the " meta-data ", to know what it contains, which class, which function, which parameter ..etc

3-a Class Function

The class method returns the class of the object, for example if there is an object from the class " School " and the object named " s ", when you use " s.class " it will return " School ".

Syntax

Object.class

3-b Class Name Function

The same as class function, this function returns the name of class of the object, we need sometimes to get the name of the class in advanced examples.

Syntax

Object.class.name

3-c Superclass Function

To get the parent class of a class you need to use the function ' superclass ', if the previous example of " School ", is applied, the object is " s " the class of this object is " School " and the parent for example is " City ", to get " City " the function " superclass " must be used.

Syntax

class.superclass

3-d Included Modules Function

This function used to get the included modules in a class, the modules are optional for the created classes

Syntax

class.included_modules 

3-e Object Id Function

Each object created has a unique number called " ID ", to distinguish them and you can call the object using its unique number, this function will get the ID of the object, if we have two objects has the same value they mean is the same object so we will get the same " ID ".

Syntax

object.object_id 

3-f Constants Function

The constants function returns an array with all the constants exist in this class, so if you create a new class and you define some constants, to get all of them you must use " constants function ".

Syntax

class.constants

3-g Local Variables Function

Each site or each program contains " Local Variables " that are defined in functions for example, to get these variables you should use " local_variables " function.

Syntax

local_variables

3-k Global Variables Function

As the " local_variables " function there is also " global_variables " function, this function returns all the global variables exist in the script, the returned form is an array.

Syntax

global_variables

3-l Methods Function

This function returns all the predefined methods exist in a specific class, for example if there is a team develop an application and someone wants to get all the methods, he can easily use this function and it will return an array.

Syntax

class.methods

s="Hola!"
#s is an object from what? 
puts s.class 
#output: String
#what is the name of this class ? 
puts s.class.name 
#output: String
#from what String  was inherited?
puts String.superclass 
#the included modules in String 
p String.included_modules 
#output: [Enumerable, Comparable, Kernel]
#each object has a unique id. 
s1="Hi" 
puts s1.object_id  #6 
s2="Hi" 
puts s2.object_id  #8 
s1="Hi" 
s2=s1 #points to s1 
puts s1.object_id #6 
puts s2.object_id #6
p Math.constants 
#output: ["E", "PI"]
#get the local variables p local_variables 
#output: ["s", "s1", "s2"]
$globString="What's up????" 
$anotherGlobString="CRUEL, WORLD!" 
#gets the global variables p global_variables
#output #["$FILENAME", "$LOADED_FEATURES", "$anotherGlobString", #  "$VERBOSE", "$globString", "$PROGRAM_NAME", "$LOAD_PATH", #  "$DEBUG", "$stdin", "$KCODE", "$stderr", "$stdout", "$defout", #  "$deferr", "$-I", "$`", "$-K", "$\\", "$_", "$!", "$\"", "$-a", "$-d", "$~", "$@", "$?", "$>", #  "$=", "$<", "$:", "$0", "$.", "$/", "$,", "$-n", #  "$*", "$SAFE", "$+", "$-p", "$&", "$'", "$$", "$-l"]
#get all of the methods in string 
methodsAry=String.methods 
p methodsAry 
#output: 
#["new", "superclass", "allocate", "inherited", "initialize_copy", ..................... #  "class_eval", ">", "<", "private_class_method", , #  "protected_methods", "nil?", "freeze", "is_a?", "eql?"]

Class hierarchy 

Ruby is one of the languages or hierarchical languages in the class system. For example, when you use the Superclass several times, you will find a class that all other classes inherited from.

class First < String  
end 
class Second < First  
end 
class Third < Second 
end 
c=Third 
while c  
   print(c)   
   print(" < ")  
   c=c.superclass  
end 
puts 
#output: Third < Second < First < String < Object

Curriculum

Part1  | Part2  | Part3

Proof of Work Done

 https://github.com/alex-harry/rubyTutorial/blob/master/ruby.rb 

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center