2012-02-03 30 views
0

我是Ruby Rails的新手。按照Ruby中的熱門程度和時間對數組進行排序

有沒有一種方法可以隨時間知道數組中元素的普及程度?

例如可以說在過去的15分鐘..

陣列具有如[ 「ABC」, 「AB」, 「ABC」, 「一個」, 「ABC」, 「AB」 ... .....]被推入陣列..我們可以得到「abc」和「ab」作爲最流行的..只是在最後15分鐘?

如果你把一整個小時..典型整個小時。「ABCD」是最流行的。應該在一個數組的形式返回「ABCD」爲最流行的元素..

是有辦法實現這一點?

+1

數組不包含在當一個要素是任何信息加入 – 2012-02-03 11:34:05

+0

同意。如果我將它保存到數據庫。有沒有辦法實現這個功能?謝謝! – gkolan 2012-02-03 11:37:11

+1

是的,但後來它成爲一個數據庫問題。分組依據,按順序,其中created_at <15.minutes.ago你明白了。 – pguardiario 2012-02-03 11:50:56

回答

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 

如果你有一箇舊版本的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 
+0

感謝您的回覆Alex!我有一個問題..它說推文中的NoMethodError#index 顯示/Users/gkolan/work/basicblog/app/views/tweets/index.html.erb其中行#15提出: 未定義的方法'reverse_each'for無:NilClass – gkolan 2012-02-07 02:25:17

+0

亞歷克斯..我對Rails很新!我是否應該在模塊TweetsHelper中創建一個名爲模塊Enumerable的助手類,例如Tweets Helper rb文件,然後在我的Tweets模型中聲明包含Enumerable?我很困惑:( – gkolan 2012-02-07 02:47:19

+1

@reko,打開命令提示符並鍵入'ruby -v'。我運行的是Ruby 1.9.2p290。我懷疑你有一個老版本的ruby,它沒有'reverse_each'。 – 2012-02-07 08:38:15