Given an IO object, you can get the “next” line with #gets, right?
Given an IO object, you can get the “current” line with #X, right? Please?
I know it’s not a common operation, but I would like tobe able to do it.
Do you mean a kind of one-line lookahead? I had occasion to do that
somewhere recently, and did:
class File
def ungets(str)
seek(pos - str.size,0)
end
# One-line lookahead.
def next_line
line = gets
ungets(line) if line
line
end
end
David
Hmmm… I might give that a go. This is the sort of thing I’m trying to do.
I’ve got the following code:
file.reverse_each do |line|
if line =~ /Published/
timestamp = collect_timestamp(line)
line = file.gets && file.gets
unless line.nil?
backend_id = collect_backend_id(line)
...
end
end
end
And I’d like to refactor it to:
file.reverse_each do |line|
if line =~ /Published/
timestamp, backend_id = collect_data(file)
end
end
def collect_data(file)
timestamp = collect_timestamp(file.current_line)
line = file.gets && file.gets
unless line.nil?
backend_id = collect_backend_id(line)
...
end
end
File#reverse_each is a nifty method I wrote to process a file in reverse line
order. I was (obviously) hoping that IO/File would have a buffer of the
current line that it can share with me! If I have to hack it, then I don’t
really achieve anything pretty.