Ruby可枚举的反向检测

前端之家收集整理的这篇文章主要介绍了Ruby可枚举的反向检测前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有以下数组:
views = [
  { :user_id => 1,:viewed_at => '2012-06-29 17:03:28 -0400' },{ :user_id => 1,:viewed_at => '2012-06-29 17:04:28 -0400' },{ :user_id => 2,:viewed_at => '2012-06-29 17:05:28 -0400' },{ :user_id => 3,:viewed_at => '2012-06-29 17:06:28 -0400' },:viewed_at => '2012-06-29 17:07:28 -0400' },:viewed_at => '2012-06-29 17:08:28 -0400' },:viewed_at => '2012-06-29 17:09:28 -0400' },:viewed_at => '2012-06-29 17:16:28 -0400' },:viewed_at => '2012-06-29 17:26:28 -0400' },:viewed_at => '2012-06-29 17:36:28 -0400' },:viewed_at => '2012-06-29 17:47:28 -0400' },:viewed_at => '2012-06-29 17:57:28 -0400' },:viewed_at => '2012-06-29 17:67:28 -0400' },:viewed_at => '2012-06-29 17:77:28 -0400' }
]

假设数组按照viewing_at排序

如果我想检索特定user_id的views数组中的最后一个视图哈希,我可以执行以下操作:

views.reverse.detect { |view| view[:user_id] == 1 }

detect将返回枚举中第一个项,其中块的计算结果为true.

我的问题是:我假设反向方法有O(n)成本,那么如何反向检测而不必反转数组呢?或者反向方法不是O(n)?

解决方法

方法数组#verse在时间和空间上是O(n).由于您不需要整个反转阵列,您可以使用 Array#reverse_each,即空间中的O(1).在实践中,这仅适用于真正的大型阵列.
views.reverse_each.detect { |view| view[:user_id] == 1 }
#=> {:user_id=>1,:viewed_at=>"2012-06-29 17:77:28 -0400"}

猜你在找的Ruby相关文章