Ruby Tutorial Part 03 String Functions, Directories and Files

in #utopian-io6 years ago (edited)

Repository

https://github.com/ruby/ruby 

What Will I Learn?

  • You will learn String Functions.
  • You will learn Directories in Ruby.
  • You will learn Files in Ruby.

Requirements

  • You need to have Ruby installed on your computer

Difficulty

  • Basic

Tutorial Contents

In this tutorial we will continue our series about Ruby, we will learn the " String functions, Directories and Files ".

1- String Functions 

a- Index and Indexing 

a-1 Indexing [ ]

In many programming languages the " String " considered as an array of characters, each box contains a character, so we can say each character indexed by a number because it's an array of characters, it starts from 0.

The string is the same like the array, it has the concept of " indexing ", the first character indexed by 0 the second by 1 and so on ..

We can simply return the ASCII code of a character using its index , and we use the " chr " function to get the value of the integer code or the ASCII code, the first character indexed by '0' and the last character by '-1'.

s= "This is Utopian"
puts s[0]#it returns the first character or the ASCII code of the first character
#output: 084
puts s[0].chr #using the chr method to convert from ASCII to character
#output: T
puts s[-1] # it returns the last character or the ASCII code of the last character
#output: 110
puts s[-1].chr #using the chr method to convert from ASCII to character
#output: n

The string variable is " s " so we use " s[index] " from [ 0 to the last one ], and it will return as I mentioned the ASCII code, we can get the characters " from to " using " string[From..To] where the " .. " means an interval from 0 to 2 " s[0..2] ".

a-2 Index Function

This method returns the index of the character passed as parameter in the string, or returns the first index it means if we have two " i " in the string it will return the index of the first " i " in the string or you can simply selecting the offset parameter.

This method accepts two parameters " the character and the offset " let's use an example.

s= "This is Utopian"
puts s.index("i") # print the index of the character "i"
#output 2
puts s[7..s.length]
puts s.index("i", 7) # the offset is 7 so it will start searching from the index number 7
#output => 12

The string is " This is Utopian ", the index of the character " i " is 2 if we start from 0 , T => 0, h => 1, i => 2 so the result will be 2, but there is another " i " in the string so this method will return just the first " i ", to get the others you must use the offset parameter.

When I added the offset " 7 " the method will start from 7 not 0 and it will return the third " i " in our example, so to get all of them you can use a " loop " and change the offset in each circle.

b- Include and Concat

b-1 Include Function

This method test if the string contains or includes the value passed as parameter or not, the value can be a " charachter " or " substring ", it returns a boolean value " True / False ", true if the string contains the value passed as parameter, else it returns false.

puts s.include?("T")  #has "T" char ?
#output: true
puts s.include?("Ut") #has "Ut" substring ?
#output: true
puts s.include?("K") #has "K" substring ?
#output: false

The method returned true because it contains the character " T " and also true because it contains the substring " Ut " and false because the character " k " doesn't exist in the string " s ".

b-2 Concat Function

The concat method adds a value ( string, character ..etc ) to the original string, we can use " << " or " += " to apply the concatenation to add something to our string, but I prefer to use this method.

str ="Hello, " 
str.concat("World!")
puts str
#output: Hello, World! 

The variable " str " is a string "Hello, ", I have used " concat " method to add another word to this string which is " world! " to print " Hello, world! ", so the string " str " has modified using this method.

c- Comparing and Scan

c-1 Comparing " eql? " Function

Sometimes we need to compare two strings " if the first equals to the second or something like that " and especially in the databases " sign in" for example, we need to compare the string entered by the user and the string in the database, for that Ruby offers us the " eql? " method that compares two strings and returns a boolean value.

usernameD = "Alex" # the username in the database
usernameU = "Alex" # the username that the user entered
puts " Welcome Alex " if usernameD.eql?(usernameU)
#output =>
Welcome Alex

If the value entered by the user equals to the value in the database I will print " Welcome Alex " or the username for example.

c-2 Scan Function

The scan function scans and returns an array depending on the value passed as parameter, we can scan and return an array of characters, or an array of words ..etc

chars = s.scan(/./)
p chars
# output => ["T", "h", "i", "s", " ", "i", "s"," ", "U", "t", "o", "p", "i", "a", "n"]
words = s.scan(/\w+/)
p words
# output => ["This", "is", "Utopian"]

In this example I have passed the "/./" to the function and it means I want to get an array of characters each box contains only one character, if I pass for example "/../" two points I mean I want to get an array each box contains two characters, and when we pass "/\+w/" it means I want to get in each box a word ..etc

d- Split and Join

d-1 Split Function

We often hear about " split " function in many programming languages, the split function will divide the string by the value passed as parameter and returns an array.

wordsS = s.split(' ') # split the space separator
p wordsS
# output => ["This", "is", "Utopian"]

I have created a variable wordsS and I maked the result of the split method ( the array ) in the wordsS variable, I have printed it and the result is an array each box contains a word from "This is Utopian" string, the separator is the " " space.

We can use the split method in dates for example, it's very important and you will always use it.

d-2 Join Function

The join function is the contrary of the " split ", as we learned the split will divide the string by the separator, the join will form a string from the array using the separator.

string = wordsS.join(" ") #join the array elements with a separator
p string
#output => This is Utopian

The wordsS is an array " ["This", "is", "Utopian"] " , I have used join with the " space " to form a string and the result is " This is Utopian ".

So we can use " split and join " to manipulate the string ( to convert the string to an array and convert the array to a string ). 

e- Gsub Function

Sometimes you need to replace a string by another string or a character by another character, for that we have the Gsub function, this function accepts two parameters " the first parameters is the string to be replaced and the second parameter is the new string ".

puts s.gsub('Utopian', 'Steemit') # replace utopian by steemit
#output => This is Steemit

I have changed the word Utopian by Steemit using the gsub method, and the result is all the string with the new word.

2- Directories

Directories are very important in any programming language and especially in Ruby, we use theme as packages or houses to store our files.

We can simply manipulate the folders by the codes that Ruby offers, pwd and getwd that are used to get the current path.

To change the folder you can just use " chdir(to) " method, this method accepts the directory as parameter.

a- Insert, Delete and Get Content

a-1 Insert Folders

The concept of inserting folders ( directories ) is very important, to insert a new directory or folder in Ruby we use the function "mkdir" or make a directory.

This function accepts two parameters, the name of the folder and the second parameter is the permission.

mkdir(new_dir_name, permissions)

a-2 Delete Folders

As we can insert a new directory, we can easily delete an existing directory and to do that we have 3 methods :

  • Delete Method : Accepts the directory name as parameter.
  • Unlink Method : Accepts the folder name as parameter.
  • Rmdir Method : Remove Directory, this function accepts the directory name as parameter.
Dir.delete(dir_name) 
Dir.unlink(dir_name)
Dir.rmdir(dir_name)

To call the functions we must use the " Dir ".

a-3 Get Content of a folder

To get the content or the files and folders inside a special directory we use the function " entries ", this function returns an array contains all the content of the directory, you can easily print them using the " loop ".

for entry in Dir.entries(Dir.getwd)
 puts entry
end
Dir.entries(Dir.getwd) {|entry|  
 puts entry
}
Dir.entries(Dir.getwd) do |entry|  
 puts entry
end

As we mentioned the function "getwd" returns the current path of the directory, the entries function accepts the path of the directory and returns its content in an array.

I have used " foreach and do " to print each element from the array using the " puts " function.

b- Directory Objects

The labels differ about creating directory objects " Dir Stream , Dir Object and Dir Handler ", the label is depending on the way to create the object " new or open ..etc " from the directory class.

The system of directories and files is when you open the file or folder, after you finish you must close it, as the sessions and many other concepts.

dirObj = Dir.open('E:\Ruby26\bin') # create new object

The open function accepts the directory path and it must be called using the " Dir ", the result is the object " dirObj ", after the process we must close the object. 

c- Directory Functions

c-1 Path Function

It returns the path of the directory with this format "  C:\ruby\bin\ ", we need this function to insert in or to delete a directory.

c-2 Tell Function

This function returns the current position of the directory.

c-3 Read Function

This function reads the next entry of the directory.

c-4 Rewind Function

It sets the current position of the directory to " 0 ", or we can say it returns the directory to the begin.

c-5 Each Function

It's used like a loop to get " each " entry, we can say also it's used for the iteration to get all the entries.

dirObj.each do |entry| # using each for literation
 puts entry
end
dirObj.each {|entry|     
 puts entry
}

Let's apply all the functions : 

dirObj=Dir.open('E:\Ruby26\bin') #open 
#dirObj=Dir.new('E:\Ruby26\bin')
puts dirObj.path
puts dirObj.tell #the current position
puts dirObj.read #next
puts dirObj.tell #the current position
puts dirObj.read #next
puts dirObj.tell #the current position
puts dirObj.read #next
#set the current position to 0
dirObj.rewind
puts dirObj.tell
dirObj.close

I have created the object " dirObj ", then I used " path " function to get the path of the directory, after that " tell " to get the position of the directory and " read " to get the next one, finally " rewind " to set the position to 0 and " close ".

3- Files

We use the files in Ruby especially with databases, we store images, files, videos ..etc, we can use the files also as a database to store something in the localhost because it's very quickly and don't need the internet connection.

We have many options to open the file, or we can say opening mode

r    => read only 
r+  => read/write
w   => write only
w+ => write/read
a    => append at the end or create
a+  => append at the start or create
b    => binary

3-a Files Functions

Delete Function

This function used to delete a file, it accepts more than one file as parameter or the file path

delete(file1,file2,file3)

Rename Function

The rename function accepts two parameters the old name which is " from " and the new name which is " to ".

rename(from,to)

Ctime Function

The creation time function, this function returns the time of creation of the file, it has the file path as parameter and it returns a time.

ctime(file_path)

Mtime Function

Last modification time function, this function returns the time of last modification for the file passed as parameter.

mtime(file_path)

Atime Function

last access time function, it returns the last time the file was opened, it has the file path as parameter.

atime(file_path)

Zero Function

This function will test if the size of the file passed as parameter is 0 or no, the earliest example is the functions created by the " touch ".

Exist Function

This function verifies if the file passed as parameter exists or not, it returns a boolean value ( True or False ).

exist?(file_path)

Readable Function

This function will test if the file passed as parameter is readable or not, it returns true or false.

readable?(file_path)

Writable Function

This function will test if the file passed as parameter is writable or not, it returns true or false.

writable?(file_path)

Executable Function

This function test if the file is executable so we can execute it or no, it returns true or false.

executable?(file_path)

Directory Function

It's used to compare if the file name passed as parameter is equal to the current file or not.

directory?(file_name)

Curriculum

Part1  | Part2

Proof of Work Done

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

Sort:  

I thank you for your contribution. Here are my thoughts. Note that, my thoughts are my personal ideas on your post and they are not directly related to the review and scoring unlike the answers I gave in the questionnaire;

  • Content

    • The content you are showing can easily be found over the internet, so keep that in mind while preparing the tutorial. You are free to do it, Utopian does not forbid it. But, Utopian appreciates unique contents more than the general concepts.

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, @yokunjon! 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 10 as payout for your posts. Your next target is to reach a total payout of 50

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:

SteemitBoard - Witness Update
SteemitBoard to support the german speaking community meetups
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 90550.33
ETH 3203.67
USDT 1.00
SBD 3.15