J
Jacob Rubynovice
Dear Rubyists,
I am a novice Ruby developer who is interested in figuring out a way to
design something like what is demonstrated below. The reason why
each_line would not work in this example is because when you pass a
block of code to the FileReader object, the memory (members of
FileReader) is not shared with the block of code that is sent to
FileReader.
Maybe I have the wrong idea for how this would be designed. I just
think it would be very convenient to do this sort of thing because I
could re-use the code to open a file and read lines and only pass it
code blocks pertainant to what I want to do with those lines of code.
Please note that I do not only want to do this for an open file/read
line script. It would also be useful if you were expanding an IP range
that exceeds what you could store into an array object because you could
write an each_host method that takes in a block of code that relates to
what you want to do to each host.
class FileReader
def initialize(fname, &block)
@filename = fname
end
def each_line(&block)
begin
source = File.new(@filename, "r")
rescue => err
exit
end
begin
while(line = source.readline)
line.strip!
if((line == "") || (line =~ /[\t+\s+]/))
next
end
block.call
end
rescue EOFError
source.close
rescue => err
puts "[!] #{err}"
exit
end
end
end
my_reader = FileReader.new(ARGV[0])
my_reader.each_line { puts line
# do more parsing stuff here
}
I am a novice Ruby developer who is interested in figuring out a way to
design something like what is demonstrated below. The reason why
each_line would not work in this example is because when you pass a
block of code to the FileReader object, the memory (members of
FileReader) is not shared with the block of code that is sent to
FileReader.
Maybe I have the wrong idea for how this would be designed. I just
think it would be very convenient to do this sort of thing because I
could re-use the code to open a file and read lines and only pass it
code blocks pertainant to what I want to do with those lines of code.
Please note that I do not only want to do this for an open file/read
line script. It would also be useful if you were expanding an IP range
that exceeds what you could store into an array object because you could
write an each_host method that takes in a block of code that relates to
what you want to do to each host.
class FileReader
def initialize(fname, &block)
@filename = fname
end
def each_line(&block)
begin
source = File.new(@filename, "r")
rescue => err
exit
end
begin
while(line = source.readline)
line.strip!
if((line == "") || (line =~ /[\t+\s+]/))
next
end
block.call
end
rescue EOFError
source.close
rescue => err
puts "[!] #{err}"
exit
end
end
end
my_reader = FileReader.new(ARGV[0])
my_reader.each_line { puts line
# do more parsing stuff here
}