如何知道我们正处于.each_slice的“最后一轮”

时间:2013-05-12 16:31:13

标签: ruby

我有一个随机的天数,我正在迭代这样:

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

并想知道我在最后一天(即上周)的时间。什么是有效的方法呢?

5 个答案:

答案 0 :(得分: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 ) )

答案 1 :(得分: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| ... }

答案 2 :(得分: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"]

答案 3 :(得分:-1)

@days.each_slice(7) { |week| if (week.last == @days.last) then <your code here> end }

答案 4 :(得分:-4)

我不知道红宝石,但是你在循环中尝试过这个吗?

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

以下是 each_slice 方法的Ruby Doc:

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