假设我有以下数组:
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.
解决方法
方法数组#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"}