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

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

    If you are willing to add some boilerplate, you can add something like this to the array class:

    class Array
      def each_fl
        each_with_index do |x,i|
          yield [i==0 ? :first : (i==length-1 ? :last : :inner), x]
        end
      end
    end
    

    and then anywhere you need to, you get the following syntax:

    [1,2,3,4].each_fl do |t,x|
      case t
        when :first
          puts "first: #{x}"
        when :last
          puts "last: #{x}"
        else
          puts "otherwise: #{x}"
      end
    end
    

    for the following output:

    first: 1
    otherwise: 2
    otherwise: 3
    last: 4
    

提交回复
热议问题