2012-02-03 59 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