Read From File

(Return Home)

Free Ruby Scripts - Ruby Script Library

View Other Scripts

Hello World Script

Ruby RMagick Thumbnails

String Replacement Script

Html Remover

Read From File

All our scripts are compatible with GoDaddy's Deluxe hosting plan. You can read our tutorial.

File Reading

Reading from a file in Ruby is one of the simplest tasks! But you have to do it all the time in good programs. Here's how:

File.open("/location/of/my/file.txt", "r") do |f|
while ! f.eof do
line = f.gets
puts line #Print the line to the screen
end
end

It's that easy! You can do whatever you want with "line" once you have it - you can read variables or user information, and do much more. For example, you can use Ruby to make a easy-to-update website. Here's how:

Website Template Machine

Okay, so we have two files, top.txt, and bottom.txt. Each contains the code for the top and bottom of the website HTML. For example:

Top.txt-->
<html><head><title>Your Title</title><meta something></head><body bgcolor="color">
Bottom.txt-->
</body></html>

Feel Free to make yours much more elaborate. But now editing either file will allow you to update your entire website instantly. Now... how do you view a page?

File.open($layouttop, "r") do |f|
while ! f.eof do
line = replacer(f.gets)
puts line
end
end

if File.exists?("#{$page}.txt")
File.open("#{$page}.txt", "r") do |f|
while ! f.eof do
line = f.gets
puts line
end
end
else
puts ""
end

File.open($layoutbottom, "r") do |f|
while ! f.eof do
line = replacer(f.gets)
puts line
end
end

Save this as whatever.cgi and now you can access your pages! Set $layouttop and $layoutbottom to your top and bottom text files. $page can be input from your CGI.