2012-02-03 2 views
0

나는 Ruby Rails 초보자입니다.Ruby에서 인기순과 시간순으로 배열 정렬

시간이 지남에 따라 배열에서 요소의 인기를 알 수있는 방법이 있습니까? 예를 들어

은 .. 최근 15 분 동안 말할 수

배열 [ "ABC", "AB", "ABC", "A", "ABC", "AB"와 같은 가지고 ... .....] 배열로 푸시됩니다. 가장 인기있는 "abc"와 "ab"를 얻을 수 있습니까? 지난 15 분 동안? 당신은 전체 시간 동안 .. 전체 시간 동안 일반적으로 가지고가는 경우에

... "ABCD"는

인가 .. 배열에서 가장 인기 요소로 "ABCD"를 반환해야합니다 .. 가장 인기 이것을 달성하는 방법이 있습니까?

+1

배열은 요소가있을 때에 대한 정보가 포함되어 있지 않습니다

module Enumerable def to_histogram result = Hash.new(0) each { |x| result[x] += 1 } result end end 

하는 당신은 기반 수 : 나는 종종이 유틸리티 기능을 사용하여 추가 –

+0

동의. 이걸 데이터베이스에 저장했다면. 이 기능을 구현할 수있는 방법이 있습니까? 감사! – gkolan

+1

예 그렇지만 데이터베이스 문제가됩니다. Group by, order by, where created_at <15.minutes.ago 당신은 아이디어를 얻습니다. – pguardiario

답변

3

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 
+0

답장을 보내 주셔서 감사합니다! 문제가 있습니다. NoMethodError in Tweets # index 표시 /Users/gkolan/work/basicblog/app/views/tweets/index.html.erb where line # 15 raised : 정의되지 않은 메서드 'reverse_each'for nil : NilClass – gkolan

+0

Alex .. 나는 Rails에 아주 익숙하다! TweetsHelper 모듈에서 Tweets Helper rb 파일과 같은 module Enumerable이라는 헬퍼 클래스를 만들고 내 트윗 모델에 Enumerable을 포함한다고 말할까요? 나는 매우 혼란 스럽다. ( – gkolan

+1

@reko, 명령 프롬프트를 열고'ruby -v'라고 입력한다. Ruby 1.9.2p290을 실행하고 있는데, 이전 버전 인'reverse_each '가 없다고 생각된다. –