辨别每个中的第一个和最后一个元素?

@example.each do |e| #do something here end 

在这里,我想对每个中的第一个和最后一个元素做一些不同的事情,我该如何实现呢? 当然我可以使用一个循环变量i并跟踪如果i==0i==@example.size但是这不是太愚蠢吗?

其中一个更好的方法是:

 @example.tap do |head, *body, tail| head.do_head_specific_task! tail.do_tail_specific_task! body.each { |segment| segment.do_body_segment_specific_task! } end 

您可以使用each_with_index ,然后使用索引来标识第一个和最后一个项目。 例如:

 @data.each_with_index do |item, index| if index == 0 # this is the first item elsif index == @data.size - 1 # this is the last item else # all other items end end 

或者,如果您愿意,可以将数组的“中间”分开,如下所示:

 # This is the first item do_something(@data.first) @data[1..-2].each do |item| # These are the middle items do_something_else(item) end # This is the last item do_something(@data.last) 

使用这两种方法时,如果列表中只有一个或两个项目,则必须注意所需的行为。

一种相当常见的方法是以下(当数组中肯定没有重复时)。

 @example.each do |e| if e == @example.first # Things elsif e == @example.last # Stuff end end 

如果您怀疑数组可能包含重复项(或者您只是喜欢此方法),则从数组中获取第一个和最后一个项,并在块外部处理它们。 使用此方法时,您还应该将对每个实例起作用的代码提取到函数中,这样您就不必重复它:

 first = @example.shift last = @example.pop # @example no longer contains those two items first.do_the_function @example.each do |e| e.do_the_function end last.do_the_function def do_the_function(item) act on item end