Ruby inject with index and brackets

前端 未结 4 1162
谎友^
谎友^ 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条回答
  •  别跟我提以往
    2021-02-12 11:12

    What is the use of these brackets?

    It's a very nice feature of ruby. I call it "destructuring array assignment", but it probably has an official name too.

    Here's how it works. Let's say you have an array

    arr = [1, 2, 3]
    

    Then you assign this array to a list of names, like this:

    a, b, c = arr
    a # => 1
    b # => 2
    c # => 3
    

    You see, the array was "destructured" into its individual elements. Now, to the each_with_index. As you know, it's like a regular each, but also returns an index. inject doesn't care about all this, it takes input elements and passes them to its block as is. If input element is an array (elem/index pair from each_with_index), then we can either take it apart in the block body

    sorted.each_with_index.inject(groups) do |group_container, pair|
      element, index = pair
    
      # or
      # element = pair[0]
      # index = pair[1]
    
      # rest of your code
    end
    

    Or destructure that array right in the block signature. Parentheses there are necessary to give ruby a hint that this is a single parameter that needs to be split in several.

    Hope this helps.

提交回复
热议问题