How can I use a while loop in such as way where I want to process the
file until EOF? thank you!
Here is my code:
mailog="/tmp/maillog"
last_record="Jul 15 22:09:10"
File.open(mailog, 'r+').each { |line|
while !mailog.eof?
if line =~ /^#{last_record}/o
p line
end
end
}
mail.scr:6: undefined method `eof?' for "/tmp/maillog":String
(NoMethodError)
from mail.scr:5:in `each'
from mail.scr:5
The difference is just precedence. But actually both are bad idioms as they do not ensure that the File object is closed properly. File.foreach is better (see above).
Ah. "do ... end" vs. "{ ... }". Yes, that was a bit confusing at
first.
They're basically the same - they signify a block being passed into
the method.
The curly-brace "{ ... }" block is generally used when you're using a
single-line of code and "do ... end" is generally a multi-line block.
Also, I always use "{ ... }" for map/collect or select/reject methods
even if they're taking multiple lines, but that's because I wrote in
Perl for ages and that's how it did it. I find that the curly-braces
stand out more and for skanky code I want to make it easy to see where
the block starts and ends. "do" and "end" tend to blend into the rest
of the code making it "prettier" because it's all text and not looking
like line-noise.
Greg
···
On Aug 17, 8:39 am, Derek Smith <derekbellnersm...@yahoo.com> wrote:
But now, what is the diff between
File.open( "maillog" ).each do |line|
and
File.open("mailog").each { |line|
one better, or more ruby standard? I did not see a diff.
Personally I like "without the do" as there is less to type.
i was leaning on the op's example... For the record, when it comes
to file handling, i do not even do shortcuts
i think i have a question for you, cool ruby hacker robert:
if i do something like,
File.open(foo).each do
blah
end
will ruby be able to cleanup the orphaned file handle?
Probably yes. But: it will certainly be later than necessary (when a
finalizer is run which may be even as late as process exit). Plus, if
you open the file again in the same interpreter instance you may face
strange effects. That may be not so important for files which are
read only, but it can create serious issues when writing files.
My stance is this: release resources as soon as possible, especially
if it is as easy as with files.
Better:
File.foreach "maillog" do |line|
i am not a fan of foreach because i do not like the method name as
used... it's like saying "for each file"??
but that is just me...
I would aesthetics not come in my way that far. But even if: you can always do
class File
class <<self
alias better_name foreach
end
end
File.better_name "foo" do |line|
...
end
Kind regards
robert
···
2009/8/18 botp <botpena@gmail.com>:
On Mon, Aug 17, 2009 at 2:50 PM, Robert > Klemme<shortcutter@googlemail.com> wrote: