Ruby inject with index and brackets

前端 未结 4 1153
谎友^
谎友^ 2021-02-12 10:34

I try to clean my Code. The first Version uses each_with_index. In the second version I tried to compact the code with the Enumerable.inject_with_index-constr

4条回答
  •  梦毁少年i
    2021-02-12 10:58

    Seems like there already some answers given with good explanation. I want to add some information regards the clear and readable.

    Instead of the solution you chose, it is also a possibility to extend Enumerable and add this functionality.

    module Enumerable
      # The block parameter is not needed but creates more readable code.
      def inject_with_index(memo = self.first, &block)
        skip = memo.equal?(self.first)
        index = 0
        self.each_entry do |entry|
          if skip
            skip = false
          else
            memo = yield(memo, index, entry)
          end
          index += 1
        end
        memo
      end
    end
    

    This way you can call inject_with_index like so:

    # m = memo, i = index, e = entry
    (1..3).inject_with_index(0) do |m, i, e|
      puts "m: #{m}, i: #{i}, e: #{e}"
      m + i + e
    end
    #=> 9
    

    If you not pass an initial value the first element will be used, thus not executing the block for the first element.

提交回复
热议问题