以下代码有效,但看起来并不像红宝石,所以我正在寻找一种更好的方法来实现同样的目标。
#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
答案 0 :(得分:4)
您可以使用partition
方法来简化代码。
http://www.ruby-doc.org/core/classes/Enumerable.html#M001496
events = page.events.sort_by(&:start_time)
upcoming, past = events.partition{|e| e.start_time >= Time.now}
event_to_show = (upcoming.count < 0) ? upcoming.first : past.last