Discriminate first and last element in each?

前端 未结 3 1820
借酒劲吻你
借酒劲吻你 2021-02-09 03:29
@example.each do |e|
  #do something here
end

Here I want to do something different with the first and last element in each, how should I achieve this?

3条回答
  •  面向向阳花
    2021-02-09 03:54

    One of the nicer approaches is:

    @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
    

提交回复
热议问题