Discriminate first and last element in each?

前端 未结 3 1811
借酒劲吻你
借酒劲吻你 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:53

    You can use each_with_index and then use the index to identify the first and last items. For example:

    @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
    

    Alternately, if you prefer you could separate the 'middle' of the array like so:

    # 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)
    

    With both these methods you have to be careful about the desired behaviour when there are only one or two items in the list.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-09 03:54

    A fairly common approach is the following (when there are certainly no duplicates in the array).

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

    If you suspect array may contain duplicates (or if you just prefer this method) then grab the first and last items out of the array, and handle them outside of the block. When using this method you should also extract the code that acts on each instance to a function so that you don't have to repeat it:

    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
    
    0 讨论(0)
提交回复
热议问题