创建自己的类,它从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