开发者

Recognizing strings of Time in ruby

This isn't much of a problem, really, it's entirely out of curiosity.

For a program I'm working on I write a information to files at certain times (currently once/day, may change), but it's done in such a way that the time for each recorded piece of information is important. As such, every time I want to take samples and append information to the file, first I append the following:

file_out.write Time.now

As an easy way of remembering exactly when each write was made.

Now here's what I'm curious about: is there a way to check if a string received from the file ("cur_line = file_in.gets", for example) is a Time stamp?

The reason this isn't a problem is that m开发者_如何学Pythony current method is simple regex:

if cur_line =~(/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/)

And seems to work perfectly for my needs. (Due to the nature of the project, and the formatting of what I write, I know that there will be no other lines in the file that include any text of format '{Day} {Month}' so I stop parsing there. Just day or just month would be insufficient and lead to false positives).

Are there other, perhaps prettier, ways of checking for the timestamps? I won't necessarily use something else (especially if you say "well you can do X but it will cause performance to suffer greatly" (not that comparisons are a great concern for performance, in this project. I'd guess that the difference would probably be negligible)).

It's just something that struck me as interesting and something I guessed there might be cool ways of doing in Ruby. :)


You can just do Time.parse cur_line, which will return the current date if the time cannot be parsed properly. Not necessarily ideal, but Time.parse is pretty powerful :)

EDIT: Interesting way to do your regexp: Before you loop over the file, declare the regular expression as so:

expression = Regexp.new("^(#{Time::RFC2822_DAY_NAME.join("|")}) (#{Time::RFC2822_MONTH_NAME.join("|")})")

Then, when you loop over each line, do: cur_line.match(expression). This will return nil if no match. An interesting (albeit longer) way to do this.


You could try to run the lines through chronic or Date.parse, but I would bet that both of these methods are less efficient than using a regular expression. The impact of that efficiency is completely relative to how much text you have to parse.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜