在 ruby 中按时间查找最近的记录
下面的代码可以工作,但看起来不太像 ruby,所以我正在寻找更好的方法来实现相同的目的。
#Grab the events from the page
events = page.events.sort_by{|e| e.start_time}
upcoming = []
past = []
events.each do |e|
if e.start_time >= Time.now
upcoming.push(e)
end
if e.start_time < Time.now
past.push(e)
end
end
# show the most nearest event (current events if exist)
event_to_show = (upcoming.count < 0) ? upcoming.first : past.last
The following code works but doesn't seem very ruby-like so I am looking for a better way to achieve the same.
#Grab the events from the page
events = page.events.sort_by{|e| e.start_time}
upcoming = []
past = []
events.each do |e|
if e.start_time >= Time.now
upcoming.push(e)
end
if e.start_time < Time.now
past.push(e)
end
end
# show the most nearest event (current events if exist)
event_to_show = (upcoming.count < 0) ? upcoming.first : past.last
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
partition
方法来简化代码。http://www.ruby-doc.org/core/classes/Enumerable .html#M001496
You can use
partition
method to simplify the code.http://www.ruby-doc.org/core/classes/Enumerable.html#M001496