Download presentation
Presentation is loading. Please wait.
1
Learning Ruby Files
2
# Example 1 - Read File and close counter = 1 file = File.new(“sowpods.txt", "r") while (line = file.gets) puts "#{counter}: #{line}“ counter = counter + 1 end file.close # Example 2 - Pass file to block File.open("readfile.rb", "r") do |infile| while (line = infile.gets) puts "#{counter}: #{line}" counter = counter + 1 end If the optional block is given on opening a file, the block will be passed a file as an argument, and the file will automatically be closed when the block terminates. Always close a file that you open. In the case of a file open for writing data may be lost if you don’t. Place input file in same directory as Ruby file (lib) There is no ++ operator
3
while line = gets reads from standard input puts “enter your line” line.gsub!(/[^ a-z]/,"") removes all non alpha characters puts line end while line = gets puts line.downcase end while line = gets puts line.downcase if line =~ /KEEP/ Use of regular expression end Pattern matching write line if matches “KEEP” The "readlines" Program
4
myfile = File.open("temp.txt") # myfile.readline "This is a test file\n“ myfile.readline "It contains some example lines\n" myfile.each {|line| print line } myfile = File.new("write.txt", "w+") open for read and write File.exists?(“temp.txt”) really there?
5
print STDOUT << "Hello" << " " << "World!" << "\n“ def readWord print("What is your guess? "); STDOUT.flush not really needed a_string = gets a_string.strip! a_string.downcase! print("You gave me '#{a_string}'") a_string end Common needs
6
p File.exists?("sowpods.txt") f=File.open("sowpods.txt") def readWord(inputFile) a_string = inputFile.readline a_string.strip! a_string.downcase! print("You gave me '#{a_string}'") a_string end 3.times{readWord(f)}
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.