Magic First and Last Indicator in a Loop in Ruby/Rails?

前端 未结 16 2348
眼角桃花
眼角桃花 2020-12-08 00:01

Ruby/Rails does lots of cool stuff when it comes to sugar for basic things, and I think there\'s a very common scenario that I was wondering if anyone has done a helper or s

16条回答
  •  一整个雨季
    2020-12-08 00:50

    As many have pointed out, each_with_index seems to be the key to this. I have this code block that I liked.

    array.each_with_index do |item,index|
      if index == 0
        # first item
      elsif index == array.length-1
        # last item
      else
        # middle items
      end
      # all items
    end
    

    Or

    array.each_with_index do |item,index|
      if index == 0
        # first item
      end
      # all items
      if index == array.length-1
        # last item
      end
    end
    

    Or by Array extensions

    class Array
    
      def each_with_position
        array.each_with_index do |item,index|
          if index == 0
            yield item, :first
          elsif index == array.length-1
            yield item, :last
          else
            yield item, :middle
          end
        end
      end
    
      def each_with_index_and_position
        array.each_with_index do |item,index|
          if index == 0
            yield item, index, :first
          elsif index == array.length-1
            yield item, index, :last
          else
            yield item, index, :middle
          end
        end
      end
    
      def each_with_position_and_index
        array.each_with_index do |item,index|
          if index == 0
            yield item, :first, index
          elsif index == array.length-1
            yield item, :last, index
          else
            yield item, :middle, index
          end
        end
      end
    
    end
    

提交回复
热议问题