Создайте свой собственный класс, который наследует от 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