創建自己的類,它從Array繼承,或將其所有功能委託給Array。例如:
class TimestampedArray
def initialize
@items = []
end
def <<(obj)
@items << [Time.now,obj]
end
# get all the items which were added in the last "seconds" seconds
# assumes that items are kept in order of add time
def all_from_last(seconds)
go_back_to = Time.now - seconds
result = []
@items.reverse_each do |(time,item)|
break if time < go_back_to
result.unshift(item)
end
result
end
end
如果你有一箇舊版本的Ruby,哪個沒有reverse_each
:
def all_from_last(seconds)
go_back_to = Time.now - seconds
result = []
(@items.length-1).downto(0) do |i|
time,item = @items[i]
break if time < go_back_to
result.unshift(item)
end
result
end
然後,你需要的東西,以找到「最流行」的項目。我經常用這個效用函數:
module Enumerable
def to_histogram
result = Hash.new(0)
each { |x| result[x] += 1 }
result
end
end
上,您可以基地:
module Enumerable
def most_popular
h = self.to_histogram
max_by { |x| h[x] }
end
end
,那麼你得到:
timestamped_array.all_from_last(3600).most_popular # "most popular" in last 1 hour
數組不包含在當一個要素是任何信息加入 – 2012-02-03 11:34:05
同意。如果我將它保存到數據庫。有沒有辦法實現這個功能?謝謝! – gkolan 2012-02-03 11:37:11
是的,但後來它成爲一個數據庫問題。分組依據,按順序,其中created_at <15.minutes.ago你明白了。 – pguardiario 2012-02-03 11:50:56