Basic IO Operations in Ruby

asha's Avatar author of Basic IO Operations in Ruby
This is an article on Basic IO Operations in Ruby in Ruby on Rails.
Ruby is one of the growing scripting & web development language, it was designed to be easy to learn and provides least possible surprises for a newcomer to the language. Ruby on Rails is a very popular and robust MVC web framework. Ruby can also be used as CGI or can be inserted into Apache as module with the help of mod_ruby.

Ruby comes in many variants, but let's leave the details of that for another day, in this article we'll discuss how the basic input/output operations such a reading from the terminal, file, writing out to a file etc. can be done in Ruby.

Reading from STDIN



Ruby has a built-in function gets() which reads a line from a file handle, in this case the STDIN. Now, let's look at a simple code which will read a line from the STDIN and print it.

Code: Ruby
#!/usr/bin/ruby

# "print" because puts adds a trailing newline
print "Enter your name: "
# read a line into the variable name
name = gets
# print
puts "Hello, #{name}"

Output:
Code:
[pradeep@desktop]$ ./test.rb
Enter your name: Pradeep
Hello, Pradeep
Let's look at another example where we'll ready the whole input line by line and print it's length.

Code: Ruby
#!/usr/bin/ruby

string = ''

while line = gets
        string = string + line
end

puts "Input was " + string.length.to_s + " character(s) long"

Output:
Code:
[pradeep@desktop]$ ./test.rb
The Quick Brown Fox Jumps Over The Lazy Dog
Wow that was quick
Input was 63 character(s) long
[pradeep@desktop]$ ./test.rb < test.rb
Input was 140 character(s) long

Reading From A File



The File object is contains the related operations for opening a file which returns the file handle object. Please follow the example below.

Code: Ruby
#!/usr/bin/ruby

# open the file for reading
file_h = File.new("data.txt", "r")

# iterate till eof
while line = file_h.gets
    puts line
end

# close the filehandle
file_h.close

Now, let me list a few file handle iterators which are unique to Ruby in the next example.

Code: Ruby
#!/usr/bin/ruby

# open the file for reading
file_h = File.new("data.txt", "r")

# the each_byte method, reads character by character
file_h.each_byte { |ch| putc ch }

# the each_line method, reads line by line, default line separator is newline
file_h.each_line { |line| puts "Read #{line.dump}" }

# specify a different line separator
file_h.each_line("|") do |line|
  puts "Read #{ line.dump }"
end

# reading a specific no. of bytes, say reading 16 bytes
data = file_h.sysread(16)

# read the whole file into an array
file_array = IO.readlines("data.txt")

Writing To A File



Writing to files with Ruby can be more fun than other languages, I guess it's because everything in Ruby is an object. There are numerous methods available to write to a file like print, printf, puts, syswrite, etc. all are called on the file handle. But remember not to mix syswrite and other methods, as syswrite works on a system level and is unbuffered, else set the file handle to be unbuffered by default. Now, follow the example below.

Code: Ruby
#!/usr/bin/ruby

# open the file for writing, you can also open it for appending with "a"
# you may also specify the Unix file permissions for a new that would be created
file_fh = File.new('data.txt','w+', 0644)

# set the file handle to turn of buffering, i.e. it will immediately write to the file
file_fh.sync = true

# write with puts, it'll append a newline in the end
file_fh.puts("My first line")

# write with print, it'll not add a newline
file_fh.print("Add with print")

# to see that there wasn't any newline added
file_fh.print("Add with another print")

# write any arbitrary string with syswrite, syswrite is faster than other methods
# it returns the number of bytes written
puts file_fh.syswrite("Trying syswrite")

# remember to close the file, specially in case of buffered mode so that
# any unbuffered data is written to the disk
file_fh.close

Hope this was helpful, enjoy coding in Ruby.