Download this source
# basic file input
# The manual way
f = open('/etc/passwd','r')
f.each do | line |
puts line
end
f.close
# The better way - here Ruby will automatically take care
# of closing the file for us when the block's done.
File.open('/etc/passwd','r') do |f|
f.each_line do | line |
puts line
end
end
# Manually, with a File object.
fo = File.new('/etc/passwd',"r")
fo.each_byte do | b |
putc b; putc '='
end
fo.close
puts
# Writing a file is best handled with that second form
# Notice how File defines the '<<' method to append to the file,
# and that it is automatically closed when the block exits.
File.open('newfile.txt','w+') do |f|
f << "Just a string"
end
# Let's just double check. We can easily slurp in a textfile by line
# using to_a (or even splat ;)).
str1 = File.open('newfile.txt','r') do |f|
puts f.to_a
end
# Using splat like this is a bit controversial apparently, but I like it -
# to me it says 'puts everything from f'.
str1 = File.open('newfile.txt','r') do |f|
puts *f
end
Running this outputs:
sample:x:100:100:sample:/home/sample:/bin/bash
[... snip ... ]
s=a=m=p=l=e=:=x=:=1=0=0=:=1=0=0=:=s=a=m=p=l=e=:=/=h=o=m=e=/=s=a=m=p=l=e=:=/=b=i=n=/=b=a=s=h=
[... snip ... ]
=
Just a string
Just a string

