3

我有随机的天数,我像这样迭代:

@days.each_slice(7) {|week|}

并且想知道我什么时候在最后几天(即上周)。什么是一种有效的方法来做到这一点?

4

5 回答 5

1
@days.each_slice(7).with_index do |week,i|
  if i == (@days.size-1)/7
    # last one
  end
  ...
end

或者,如果您在块中的代码在上周存在很大差异:

weeks = @days.each_slice(7).to_a
weeks[0...-1].each {|week| ... }
weeks[-1].tap {|last_week| ... }
于 2013-05-12T22:12:15.237 回答
1

我能想到的最简单的方法是定义这个算法来检测数组的最后一个切片:

def last_slice( array, i )
    last_slice = (array.count % i == 0) ? i : array.count % i
    array.last( last_slice )
end

然后像这样比较它:

if ( week == last_slice( @days, 7 ) )
于 2013-05-12T16:48:08.147 回答
0

这是一个提示,希望对您有所帮助:

ar = [1,2,3,1,2,3,"a","b","c"]
e = ar.each_slice(3)
e.size.times do |i|
 begin
  i = e.next
  e.peek
 rescue StopIteration
  p "reached last iteration : #{i}"
 end
end
#=> "reached last iteration : [\"a\", \"b\", \"c\"]"

或者您可以执行以下操作:

e = ar.each_slice(3)
e.with_index{|i,ind| p i if ind == e.size - 1 }
#=> ["a", "b", "c"]

或者您也可以执行以下操作:

ar = [1,2,3,1,5,3,"a","b","c"]
e = ar.each_slice(3)
e.size.times{|i| i = e.next;p i if !(e.peek rescue nil) }
#=> ["a", "b", "c"]
于 2013-05-12T17:24:24.693 回答
-1
@days.each_slice(7) { |week| if (week.last == @days.last) then <your code here> end }
于 2013-05-12T16:51:48.550 回答
-4

我不了解红宝石,但您是否在循环中尝试过这个?

@days.each_slice(7) {|week|
    if week.last # do stuff...
}

这是each_slice方法的 Ruby 文档:

http://ruby-doc.org/core-2.0/Enumerable.html#method-i-each_slice

于 2013-05-12T16:43:04.363 回答