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
당신은 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 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
배열은 요소가있을 때에 대한 정보가 포함되어 있지 않습니다
이하는 당신은 기반 수 : 나는 종종이 유틸리티 기능을 사용하여 추가 –
동의. 이걸 데이터베이스에 저장했다면. 이 기능을 구현할 수있는 방법이 있습니까? 감사! – gkolan
예 그렇지만 데이터베이스 문제가됩니다. Group by, order by, where created_at <15.minutes.ago 당신은 아이디어를 얻습니다. – pguardiario