在Ruby中按流行度和时间排序数组

时间:2012-02-03 11:30:48

标签: ruby arrays

我是Ruby Rails的新手。

有没有办法知道数组中元素的流行程度?

例如,让我们说最近15分钟..

阵列有像[“abc”,“ab”,“abc”,“a”,“abc”,“ab”........]被推入数组......我们可以得到“abc”和“ab”是最受欢迎的......仅仅是最后15分钟?

如果你需要一整个小时...典型的整个小时..“abcd”是最受欢迎的..它应该返回“abcd”作为数组中最受欢迎的元素..

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分: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
相关问题