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

前端 未结 16 2343
眼角桃花
眼角桃花 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:43

    Partition the array into ranges where elements within each range are supposed to behave different. Map each range thus created to a block.

    class PartitionEnumerator
        include RangeMaker
    
        def initialize(array)
            @array = array
            @handlers = {}
        end
    
        def add(range, handler)
            @handlers[range] = handler
        end
    
        def iterate
            @handlers.each_pair do |range, handler|
              @array[range].each { |value| puts handler.call(value) }
            end
        end
    end
    

    Could create ranges by hand, but these helpers below make it easier:

    module RangeMaker
      def create_range(s)
        last_index = @array.size - 1
        indexes = (0..last_index)
        return (indexes.first..indexes.first) if s == :first
        return (indexes.second..indexes.second_last) if s == :middle
        return (indexes.last..indexes.last) if s == :last
      end  
    end
    
    class Range
      def second
        self.first + 1
      end
    
      def second_last
        self.last - 1
      end
    end
    

    Usage:

    a = [1, 2, 3, 4, 5, 6]
    
    e = PartitionEnumerator.new(a)
    e.add(e.create_range(:first), Proc.new { |x| x + 1 } )
    e.add(e.create_range(:middle), Proc.new { |x| x * 10 } )
    e.add(e.create_range(:last), Proc.new { |x| x } )
    
    e.iterate
    

提交回复
热议问题