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

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

    If you don't mind that the "last" action happens before the stuff in the middle, then this monkey-patch:

    class Array
    
      def for_first
        return self if empty?
        yield(first)
        self[1..-1]
      end
    
      def for_last
        return self if empty?
        yield(last)
        self[0...-1]
      end
    
    end
    

    Allows this:

    %w(a b c d).for_first do |e|
      p ['first', e]
    end.for_last do |e|
      p ['last', e]
    end.each do |e|
      p ['middle', e]
    end
    
    # => ["first", "a"]
    # => ["last", "d"]
    # => ["middle", "b"]
    # => ["middle", "c"]
    

提交回复
热议问题