SlideShare a Scribd company logo
RUBY FILE I/O, DIRECTORIES
http://www.tutorialspoint.com/ruby/ruby_input_output.htm                                           Copyright © tutorialspoint.com



Ruby provides a whole set of I/O-related methods implemented in the Kernel module. All the I/O methods are derived
from the class IO.

The class IO provides all the basic methods, such as read, write, gets, puts, readline, getc, and printf .

This chapter will cover all ithe basic I/O functions available in Ruby. For more functions please refere to Ruby Class
IO.

The puts Statement:

In previous chapters, you assigned values to variables and then printed the output using puts statement.

The puts statement instructs the program to display the value stored in the variable. This will add a new line at the end
of each line it writes.

Example:

 #!/usr/bin/ruby

 val1   = "This is variable one"
 val2   = "This is variable two"
 puts   val1
 puts   val2


This will produce following result:

 This is variable one
 This is variable two


The gets Statement:

The gets statement can be used to take any input from the user from standard screen called STDIN.

Example:

The following code shows you how to use the gets statement. This code will prompt the user to enter a value, which
will be stored in a variable val and finally will be printed on STDOUT.

 #!/usr/bin/ruby

 puts "Enter a value :"
 val = gets
 puts val


This will produce following result:

 Enter a value :
 This is entered value
 This is entered value


The putc Statement:

Unlike the puts statement, which outputs the entire string onto the screen, the putc statement can be used to output one
character at a time.

Example:

The output of the following code is just the character H:

 #!/usr/bin/ruby

 str="Hello Ruby!"
 putc str


This will produce following result:

 H


The print Statement:

The print statement is similar to the puts statement. The only difference is that the puts statement goes to the next line
after printing the contents, whereas with the print statement the cursor is positioned on the same line.

Example:

 #!/usr/bin/ruby

 print "Hello World"
 print "Good Morning"


This will produce following result:

 Hello WorldGood Morning


Opening and Closing Files:

Until now, you have been reading and writing to the standard input and output. Now we will see how to play with actual
data files.

The File.new Method:

You can create a File object using File.new method for reading, writing, or both, according to the mode string. Finally
you can use File.close method to close that file.

Syntax:

 aFile = File.new("filename", "mode")
    # ... process the file
 aFile.close


The File.open Method:

You can use File.open method to create a new file object and assign that file object to a file. However, there is one
difference in between File.open and File.new methods. The difference is that the File.open method can be associated
with a block, whereas you cannot do the same using the File.new method.

 File.open("filename", "mode") do |aFile|
    # ... process the file
 end
Here is a list of The Different Modes of Opening a File:



 Modes      Description

 r          Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode.

 r+         Read-write mode. The file pointer will be at the beginning of the file.

 w          Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for
            writing.

 w+         Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file
            for reading and writing.

 a          Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append
            mode. If the file does not exist, it creates a new file for writing.

 a+         Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the
            append mode. If the file does not exist, it creates a new file for reading and writing.



Reading and Writing Files:

The same methods that we've been using for 'simple' I/O are available for all file objects. So, gets reads a line from
standard input, and aFile.gets reads a line from the file object aFile.

However, I/O objects provides additional set of access methods to make our lives easier.

The sysread Method:

You can use the method sysread to read the contents of a file. You can open the file in any of the modes when using the
method sysread. For example :

 #!/usr/bin/ruby

 aFile = File.new("/var/www/tutorialspoint/ruby/test", "r")
 if aFile
    content = aFile.sysread(20)
    puts content
 else
    puts "Unable to open file!"
 end


This statement will output the first 20 characters of the file. The file pointer will now be placed at the 21st character in
the file.

The syswrite Method:

You can use the method syswrite to write the contents into a file. You need to open the file in write mode when using
the method syswrite. For example :

 #!/usr/bin/ruby

 aFile = File.new("/var/www/tutorialspoint/ruby/test", "r+")
 if aFile
    aFile.syswrite("ABCDEF")
 else
    puts "Unable to open file!"
 end
This statement will write "ABCDEF" into the file.

The each_byte Method:

This method belongs to the class File. The method each_byte is always associated with a block. Consider the following
code sample: :

 #!/usr/bin/ruby

 aFile = File.new("/var/www/tutorialspoint/ruby/test", "r")
 if aFile
    aFile.syswrite("ABCDEF")
    aFile.each_byte {|ch| putc ch; putc ?. }
 else
    puts "Unable to open file!"
 end


Characters are passed one by one to the variable ch and then displayed on the screen as follows:

 T.h.i.s. .i.s. .l.i.n.e. .o.n.e.
 .T.h.i.s. .i.s. .l.i.n.e. .t.w.o.
 .T.h.i.s. .i.s. .l.i.n.e. .t.h.r.e.e.
 .A.n.d. .s.o. .o.n.......


The IO.readlines Method:

The class File is a subclass of the class IO. The class IO also has some methods which can be used to manipulate files.

One of the IO class methods is IO.readlines. This method returns the contents of the file line by line. The following
code displays the use of the method IO.readlines:

 #!/usr/bin/ruby

 arr = IO.readlines("/var/www/tutorialspoint/ruby/test")
 puts arr[0]
 puts arr[1]


In this code, the variable arr is an array. Each line of the file test will be an element in the array arr. Therefore, arr[0]
will contain the first line, whereas arr[1] will contain the second line of the file.

The IO.foreach Method:

This method also returns output line by line. The difference between the method foreach and the method readlines is
that the method foreach is associated with a block. However, unlike the method readlines, the method foreach does not
return an array. For example:

 #!/usr/bin/ruby

 IO.foreach("test"){|block| puts block}


This code will pass the contents of the file test line by line to the variable block, and then the output will be displayed
on the screen.

Renaming and Deleting Files:

You can rename and delete files programmatically with Ruby with the rename and delete methods.

Following is the example to rename an existing file test1.txt:
#!/usr/bin/ruby

 # Rename a file from test1.txt to test2.txt
 File.rename( "test1.txt", "test2.txt" )



Following is the example to delete an existing file test2.txt:

 #!/usr/bin/ruby

 # Delete file test2.txt
 File.delete("text2.txt")


File Modes and Ownership:

Use the chmod method with a mask to change the mode or permissions/access list of a file:

Following is the example to change mode of an existing file test.txt to a mask value:

 #!/usr/bin/ruby

 file = File.new( "test.txt", "w" )
 file.chmod( 0755 )


Following is the table which can help you to choose different mask for chmod method:



 Mask                           Description

 0700                           rwx mask for owner

 0400                           r for owner

 0200                           w for owner

 0100                           x for owner

 0070                           rwx mask for group

 0040                           r for group

 0020                           w for group

 0010                           x for group

 0007                           rwx mask for other

 0004                           r for other

 0002                           w for other

 0001                           x for other

 4000                           Set user ID on execution

 2000                           Set group ID on execution

 1000                           Save swapped text, even after use
File Inquiries:

The following command tests whether a file exists before opening it:

 #!/usr/bin/ruby

 File.open("file.rb") if File::exists?( "file.rb" )


The following command inquire whether the file is really a file:

 #!/usr/bin/ruby

 # This returns either true or false
 File.file?( "text.txt" )


The following command finds out if it given file name is a directory:

 #!/usr/bin/ruby

 # a directory
 File::directory?( "/usr/local/bin" ) # => true

 # a file
 File::directory?( "file.rb" ) # => false


The following command finds whether the file is readable, writable or executable:

 #!/usr/bin/ruby

 File.readable?( "test.txt" )   # => true
 File.writable?( "test.txt" )   # => true
 File.executable?( "test.txt" ) # => false


The following command finds whether the file has zero size or not:

 #!/usr/bin/ruby

 File.zero?( "test.txt" )              # => true


The following command returns size of the file :

 #!/usr/bin/ruby

 File.size?( "text.txt" )            # => 1002


The following command can be used to find out a type of file :

 #!/usr/bin/ruby

 File::ftype( "test.txt" )             # => file


The ftype method identifies the type of the file by returning one of the following: file, directory, characterSpecial,
blockSpecial, fifo, link, socket, or unknown.

The following command can be used to find when a file was created, modified, or last accessed :

 #!/usr/bin/ruby

 File::ctime( "test.txt" ) # => Fri May 09 10:06:37 -0700 2008
 File::mtime( "text.txt" ) # => Fri May 09 10:44:44 -0700 2008
 File::atime( "text.txt" ) # => Fri May 09 10:45:01 -0700 2008
Directories in Ruby:

All files are contained within various directories, and Ruby has no problem handling these too. Whereas the File class
handles files, directories are handled with the Dir class.

Navigating Through Directories:

To change directory within a Ruby program, use Dir.chdir as follows. This example changes the current directory to
/usr/bin.

 Dir.chdir("/usr/bin")


You can find out what the current directory is with Dir.pwd:

 puts Dir.pwd # This will return something like /usr/bin


You can get a list of the files and directories within a specific directory using Dir.entries:

 puts Dir.entries("/usr/bin").join(' ')


Dir.entries returns an array with all the entries within the specified directory. Dir.foreach provides the same feature:

 Dir.foreach("/usr/bin") do |entry|
    puts entry
 end


An even more concise way of getting directory listings is by using Dir's class array method:

 Dir["/usr/bin/*"]


Creating a Directory:

The Dir.mkdir can be used to create directories:

 Dir.mkdir("mynewdir")


You can also set permissions on a new directory (not one that already exists) with mkdir:

NOTE: The mask 755 sets permissions owner, group, world [anyone] to rwxr-xr-x where r = read, w = write, and x =
execute.

 Dir.mkdir( "mynewdir", 755 )


Deleting a Directory:

The Dir.delete can be used to delete a directory. The Dir.unlink and Dir.rmdir perform exactly the same function and
are provided for convenience.

 Dir.delete("testdir")


Creating Files & Temporary Directories:

Temporary files are those that might be created briefly during a program's execution but aren't a permanent store of
information.
Dir.tmpdir provides the path to the temporary directory on the current system, although the method is not available by
default. To make Dir.tmpdir available it's necessary to use require 'tmpdir'.

You can use Dir.tmpdir with File.join to create a platform-independent temporary file:

 require 'tmpdir'
    tempfilename = File.join(Dir.tmpdir, "tingtong")
    tempfile = File.new(tempfilename, "w")
    tempfile.puts "This is a temporary file"
    tempfile.close
    File.delete(tempfilename)


This code creates a temporary file, writes data to it, and deletes it. Ruby's standard library also includes a library called
Tempfile that can create temporary files for you:

 require 'tempfile'
    f = Tempfile.new('tingtong')
    f.puts "Hello"
    puts f.path
    f.close


Built-in Functions:

Here is the complete list of ruby buil-in functions to process files and directories:

       File Class and Methods.

       Dir Class and Methods.

More Related Content

What's hot (20)

File handling in c++
File handling in c++File handling in c++
File handling in c++
Daniel Nyagechi
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
Python - Lecture 8
Python - Lecture 8Python - Lecture 8
Python - Lecture 8
Ravi Kiran Khareedi
 
Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell Scripting
Jaibeer Malik
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
Krasimir Berov (Красимир Беров)
 
Perl Programming - 01 Basic Perl
Perl Programming - 01 Basic PerlPerl Programming - 01 Basic Perl
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
Gaurav Shinde
 
Bash shell
Bash shellBash shell
Bash shell
xylas121
 
Basics of shell programming
Basics of shell programmingBasics of shell programming
Basics of shell programming
Chandan Kumar Rana
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
baabtra.com - No. 1 supplier of quality freshers
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell Scripting
Open Gurukul
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
keeeerty
 
php&mysql with Ethical Hacking
php&mysql with Ethical Hackingphp&mysql with Ethical Hacking
php&mysql with Ethical Hacking
BCET
 
Unix shell scripts
Unix shell scriptsUnix shell scripts
Unix shell scripts
Prakash Lambha
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
Vineeta Garg
 
Chap06
Chap06Chap06
Chap06
Dr.Ravi
 
Shellscripting
ShellscriptingShellscripting
Shellscripting
Narendra Sisodiya
 

Viewers also liked (8)

16 ruby hashes
16 ruby hashes16 ruby hashes
16 ruby hashes
Walker Maidana
 
19 ruby iterators
19 ruby iterators19 ruby iterators
19 ruby iterators
Walker Maidana
 
Ruby File I/O
Ruby File I/ORuby File I/O
Ruby File I/O
Sarah Allen
 
17 ruby date time
17 ruby date time17 ruby date time
17 ruby date time
Walker Maidana
 
15 ruby arrays
15 ruby arrays15 ruby arrays
15 ruby arrays
Walker Maidana
 
18 ruby ranges
18 ruby ranges18 ruby ranges
18 ruby ranges
Walker Maidana
 
14 ruby strings
14 ruby strings14 ruby strings
14 ruby strings
Walker Maidana
 
8 Key Life and Leadership Lessons
8 Key Life and Leadership Lessons8 Key Life and Leadership Lessons
8 Key Life and Leadership Lessons
Stanford Graduate School of Business
 

Similar to 20 ruby input output (20)

9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
Deepak Hagadur Bheemaraju
 
Files IO
Files IOFiles IO
Files IO
Blazing Cloud
 
00 ruby tutorial
00 ruby tutorial00 ruby tutorial
00 ruby tutorial
Walker Maidana
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
Bindesh Vijayan
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
ppparthpatel123
 
06 ruby variables
06 ruby variables06 ruby variables
06 ruby variables
Walker Maidana
 
ruby
rubyruby
ruby
mahersaif
 
ruby
rubyruby
ruby
mahersaif
 
a course
a coursea course
a course
mahersaif
 
اليوم السعيد
اليوم السعيداليوم السعيد
اليوم السعيد
mahersaif
 
دورتنا
دورتنادورتنا
دورتنا
mahersaif
 
ruby
rubyruby
ruby
mahersaif
 
I Love Ruby
I Love RubyI Love Ruby
I Love Ruby
mahersaif
 
I Love Ruby
I Love RubyI Love Ruby
I Love Ruby
mahersaif
 
ruby
rubyruby
ruby
mahersaif
 
Week5
Week5Week5
Week5
reneedv
 
ACM Init() lesson 1
ACM Init() lesson 1ACM Init() lesson 1
ACM Init() lesson 1
UCLA Association of Computing Machinery
 
Learn Ruby Programming in Amc Square Learning
Learn Ruby Programming in Amc Square LearningLearn Ruby Programming in Amc Square Learning
Learn Ruby Programming in Amc Square Learning
ASIT Education
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
Kushal Jangid
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
Harkamal Singh
 

More from Walker Maidana (14)

13 ruby modules
13 ruby modules13 ruby modules
13 ruby modules
Walker Maidana
 
12 ruby blocks
12 ruby blocks12 ruby blocks
12 ruby blocks
Walker Maidana
 
11 ruby methods
11 ruby methods11 ruby methods
11 ruby methods
Walker Maidana
 
10 ruby loops
10 ruby loops10 ruby loops
10 ruby loops
Walker Maidana
 
09 ruby if else
09 ruby if else09 ruby if else
09 ruby if else
Walker Maidana
 
08 ruby comments
08 ruby comments08 ruby comments
08 ruby comments
Walker Maidana
 
07 ruby operators
07 ruby operators07 ruby operators
07 ruby operators
Walker Maidana
 
05 ruby classes
05 ruby classes05 ruby classes
05 ruby classes
Walker Maidana
 
04 ruby syntax
04 ruby syntax04 ruby syntax
04 ruby syntax
Walker Maidana
 
03 ruby environment
03 ruby environment03 ruby environment
03 ruby environment
Walker Maidana
 
01 index
01 index01 index
01 index
Walker Maidana
 
02 ruby overview
02 ruby overview02 ruby overview
02 ruby overview
Walker Maidana
 
21 ruby exceptions
21 ruby exceptions21 ruby exceptions
21 ruby exceptions
Walker Maidana
 
Tutorial ruby eustaquio taq rangel
Tutorial ruby   eustaquio taq rangelTutorial ruby   eustaquio taq rangel
Tutorial ruby eustaquio taq rangel
Walker Maidana
 

Recently uploaded (20)

AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
System Card: Claude Opus 4 & Claude Sonnet 4
System Card: Claude Opus 4 & Claude Sonnet 4System Card: Claude Opus 4 & Claude Sonnet 4
System Card: Claude Opus 4 & Claude Sonnet 4
Razin Mustafiz
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025
Splunk
 
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Eugene Fidelin
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCPMCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
Sambhav Kothari
 
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 ProfessioMaster tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Kari Kakkonen
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AIAI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
Buhake Sindi
 
What is DePIN? The Hottest Trend in Web3 Right Now!
What is DePIN? The Hottest Trend in Web3 Right Now!What is DePIN? The Hottest Trend in Web3 Right Now!
What is DePIN? The Hottest Trend in Web3 Right Now!
cryptouniversityoffi
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
System Card: Claude Opus 4 & Claude Sonnet 4
System Card: Claude Opus 4 & Claude Sonnet 4System Card: Claude Opus 4 & Claude Sonnet 4
System Card: Claude Opus 4 & Claude Sonnet 4
Razin Mustafiz
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025
Splunk
 
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Marko.js - Unsung Hero of Scalable Web Frameworks (DevDays 2025)
Eugene Fidelin
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCPMCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
Sambhav Kothari
 
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 ProfessioMaster tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Master tester AI toolbox - Kari Kakkonen at Testaus ja AI 2025 Professio
Kari Kakkonen
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AIAI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
Buhake Sindi
 
What is DePIN? The Hottest Trend in Web3 Right Now!
What is DePIN? The Hottest Trend in Web3 Right Now!What is DePIN? The Hottest Trend in Web3 Right Now!
What is DePIN? The Hottest Trend in Web3 Right Now!
cryptouniversityoffi
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 

20 ruby input output

  • 1. RUBY FILE I/O, DIRECTORIES http://www.tutorialspoint.com/ruby/ruby_input_output.htm Copyright © tutorialspoint.com Ruby provides a whole set of I/O-related methods implemented in the Kernel module. All the I/O methods are derived from the class IO. The class IO provides all the basic methods, such as read, write, gets, puts, readline, getc, and printf . This chapter will cover all ithe basic I/O functions available in Ruby. For more functions please refere to Ruby Class IO. The puts Statement: In previous chapters, you assigned values to variables and then printed the output using puts statement. The puts statement instructs the program to display the value stored in the variable. This will add a new line at the end of each line it writes. Example: #!/usr/bin/ruby val1 = "This is variable one" val2 = "This is variable two" puts val1 puts val2 This will produce following result: This is variable one This is variable two The gets Statement: The gets statement can be used to take any input from the user from standard screen called STDIN. Example: The following code shows you how to use the gets statement. This code will prompt the user to enter a value, which will be stored in a variable val and finally will be printed on STDOUT. #!/usr/bin/ruby puts "Enter a value :" val = gets puts val This will produce following result: Enter a value : This is entered value This is entered value The putc Statement: Unlike the puts statement, which outputs the entire string onto the screen, the putc statement can be used to output one
  • 2. character at a time. Example: The output of the following code is just the character H: #!/usr/bin/ruby str="Hello Ruby!" putc str This will produce following result: H The print Statement: The print statement is similar to the puts statement. The only difference is that the puts statement goes to the next line after printing the contents, whereas with the print statement the cursor is positioned on the same line. Example: #!/usr/bin/ruby print "Hello World" print "Good Morning" This will produce following result: Hello WorldGood Morning Opening and Closing Files: Until now, you have been reading and writing to the standard input and output. Now we will see how to play with actual data files. The File.new Method: You can create a File object using File.new method for reading, writing, or both, according to the mode string. Finally you can use File.close method to close that file. Syntax: aFile = File.new("filename", "mode") # ... process the file aFile.close The File.open Method: You can use File.open method to create a new file object and assign that file object to a file. However, there is one difference in between File.open and File.new methods. The difference is that the File.open method can be associated with a block, whereas you cannot do the same using the File.new method. File.open("filename", "mode") do |aFile| # ... process the file end
  • 3. Here is a list of The Different Modes of Opening a File: Modes Description r Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode. r+ Read-write mode. The file pointer will be at the beginning of the file. w Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. w+ Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. a Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. a+ Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. Reading and Writing Files: The same methods that we've been using for 'simple' I/O are available for all file objects. So, gets reads a line from standard input, and aFile.gets reads a line from the file object aFile. However, I/O objects provides additional set of access methods to make our lives easier. The sysread Method: You can use the method sysread to read the contents of a file. You can open the file in any of the modes when using the method sysread. For example : #!/usr/bin/ruby aFile = File.new("/var/www/tutorialspoint/ruby/test", "r") if aFile content = aFile.sysread(20) puts content else puts "Unable to open file!" end This statement will output the first 20 characters of the file. The file pointer will now be placed at the 21st character in the file. The syswrite Method: You can use the method syswrite to write the contents into a file. You need to open the file in write mode when using the method syswrite. For example : #!/usr/bin/ruby aFile = File.new("/var/www/tutorialspoint/ruby/test", "r+") if aFile aFile.syswrite("ABCDEF") else puts "Unable to open file!" end
  • 4. This statement will write "ABCDEF" into the file. The each_byte Method: This method belongs to the class File. The method each_byte is always associated with a block. Consider the following code sample: : #!/usr/bin/ruby aFile = File.new("/var/www/tutorialspoint/ruby/test", "r") if aFile aFile.syswrite("ABCDEF") aFile.each_byte {|ch| putc ch; putc ?. } else puts "Unable to open file!" end Characters are passed one by one to the variable ch and then displayed on the screen as follows: T.h.i.s. .i.s. .l.i.n.e. .o.n.e. .T.h.i.s. .i.s. .l.i.n.e. .t.w.o. .T.h.i.s. .i.s. .l.i.n.e. .t.h.r.e.e. .A.n.d. .s.o. .o.n....... The IO.readlines Method: The class File is a subclass of the class IO. The class IO also has some methods which can be used to manipulate files. One of the IO class methods is IO.readlines. This method returns the contents of the file line by line. The following code displays the use of the method IO.readlines: #!/usr/bin/ruby arr = IO.readlines("/var/www/tutorialspoint/ruby/test") puts arr[0] puts arr[1] In this code, the variable arr is an array. Each line of the file test will be an element in the array arr. Therefore, arr[0] will contain the first line, whereas arr[1] will contain the second line of the file. The IO.foreach Method: This method also returns output line by line. The difference between the method foreach and the method readlines is that the method foreach is associated with a block. However, unlike the method readlines, the method foreach does not return an array. For example: #!/usr/bin/ruby IO.foreach("test"){|block| puts block} This code will pass the contents of the file test line by line to the variable block, and then the output will be displayed on the screen. Renaming and Deleting Files: You can rename and delete files programmatically with Ruby with the rename and delete methods. Following is the example to rename an existing file test1.txt:
  • 5. #!/usr/bin/ruby # Rename a file from test1.txt to test2.txt File.rename( "test1.txt", "test2.txt" ) Following is the example to delete an existing file test2.txt: #!/usr/bin/ruby # Delete file test2.txt File.delete("text2.txt") File Modes and Ownership: Use the chmod method with a mask to change the mode or permissions/access list of a file: Following is the example to change mode of an existing file test.txt to a mask value: #!/usr/bin/ruby file = File.new( "test.txt", "w" ) file.chmod( 0755 ) Following is the table which can help you to choose different mask for chmod method: Mask Description 0700 rwx mask for owner 0400 r for owner 0200 w for owner 0100 x for owner 0070 rwx mask for group 0040 r for group 0020 w for group 0010 x for group 0007 rwx mask for other 0004 r for other 0002 w for other 0001 x for other 4000 Set user ID on execution 2000 Set group ID on execution 1000 Save swapped text, even after use
  • 6. File Inquiries: The following command tests whether a file exists before opening it: #!/usr/bin/ruby File.open("file.rb") if File::exists?( "file.rb" ) The following command inquire whether the file is really a file: #!/usr/bin/ruby # This returns either true or false File.file?( "text.txt" ) The following command finds out if it given file name is a directory: #!/usr/bin/ruby # a directory File::directory?( "/usr/local/bin" ) # => true # a file File::directory?( "file.rb" ) # => false The following command finds whether the file is readable, writable or executable: #!/usr/bin/ruby File.readable?( "test.txt" ) # => true File.writable?( "test.txt" ) # => true File.executable?( "test.txt" ) # => false The following command finds whether the file has zero size or not: #!/usr/bin/ruby File.zero?( "test.txt" ) # => true The following command returns size of the file : #!/usr/bin/ruby File.size?( "text.txt" ) # => 1002 The following command can be used to find out a type of file : #!/usr/bin/ruby File::ftype( "test.txt" ) # => file The ftype method identifies the type of the file by returning one of the following: file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown. The following command can be used to find when a file was created, modified, or last accessed : #!/usr/bin/ruby File::ctime( "test.txt" ) # => Fri May 09 10:06:37 -0700 2008 File::mtime( "text.txt" ) # => Fri May 09 10:44:44 -0700 2008 File::atime( "text.txt" ) # => Fri May 09 10:45:01 -0700 2008
  • 7. Directories in Ruby: All files are contained within various directories, and Ruby has no problem handling these too. Whereas the File class handles files, directories are handled with the Dir class. Navigating Through Directories: To change directory within a Ruby program, use Dir.chdir as follows. This example changes the current directory to /usr/bin. Dir.chdir("/usr/bin") You can find out what the current directory is with Dir.pwd: puts Dir.pwd # This will return something like /usr/bin You can get a list of the files and directories within a specific directory using Dir.entries: puts Dir.entries("/usr/bin").join(' ') Dir.entries returns an array with all the entries within the specified directory. Dir.foreach provides the same feature: Dir.foreach("/usr/bin") do |entry| puts entry end An even more concise way of getting directory listings is by using Dir's class array method: Dir["/usr/bin/*"] Creating a Directory: The Dir.mkdir can be used to create directories: Dir.mkdir("mynewdir") You can also set permissions on a new directory (not one that already exists) with mkdir: NOTE: The mask 755 sets permissions owner, group, world [anyone] to rwxr-xr-x where r = read, w = write, and x = execute. Dir.mkdir( "mynewdir", 755 ) Deleting a Directory: The Dir.delete can be used to delete a directory. The Dir.unlink and Dir.rmdir perform exactly the same function and are provided for convenience. Dir.delete("testdir") Creating Files & Temporary Directories: Temporary files are those that might be created briefly during a program's execution but aren't a permanent store of information.
  • 8. Dir.tmpdir provides the path to the temporary directory on the current system, although the method is not available by default. To make Dir.tmpdir available it's necessary to use require 'tmpdir'. You can use Dir.tmpdir with File.join to create a platform-independent temporary file: require 'tmpdir' tempfilename = File.join(Dir.tmpdir, "tingtong") tempfile = File.new(tempfilename, "w") tempfile.puts "This is a temporary file" tempfile.close File.delete(tempfilename) This code creates a temporary file, writes data to it, and deletes it. Ruby's standard library also includes a library called Tempfile that can create temporary files for you: require 'tempfile' f = Tempfile.new('tingtong') f.puts "Hello" puts f.path f.close Built-in Functions: Here is the complete list of ruby buil-in functions to process files and directories: File Class and Methods. Dir Class and Methods.