Ruby Tutorial Part 04 Writing, Exceptions and Reflection

in #utopian-io6 years ago (edited)

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 

Sort:  

Thank you for your contribution @alex-harry.
After reviewing your contribution, we suggest you following points:

  • Your tutorial is very well structured and explained. Good job!

  • The speed of presentation of the results in the GIFs is a bit quick, sometimes I need to see more than once what you've been doing in the terminal.

  • The information in your tutorial is easy to find on the internet, however it is very well explained.

  • Thanks for following some of our suggestions from your previous tutorial.

Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Congratulations @alex-harry! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 50 as payout for your posts. Your next target is to reach a total payout of 100

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Do not miss the last post from @steemitboard:

New japanese speaking community Steem Meetup badge
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Hi @alex-harry!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @alex-harry!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.22
TRX 0.20
JST 0.035
BTC 91483.13
ETH 3152.10
USDT 1.00
SBD 3.10