Ruby inject with index and brackets

前端 未结 4 1148
谎友^
谎友^ 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 10:57

    What is the use of these brackets?

    To understand the brackets, first you need to understand how destruction works in ruby. The simplest example I can think of this this:

    1.8.7 :001 > [[1,3],[2,4]].each do |a,b|
    1.8.7 :002 >     puts a, b
    1.8.7 :003?>   end
    1
    3
    2
    4
    

    You should know how each function works, and that the block receives one parameter. So what happens when you pass two parameters? It takes the first element [1,3] and try to split (destruct) it in two, and the result is a=1 and b=3.

    Now, inject takes two arguments in the block parameter, so it is usually looks like |a,b|. So passing a parameter like |group_container, (element,index)| we are in fact taking the first one as any other, and destructing the second in two others (so, if the second parameter is [1,3], element=1 and index=3). The parenthesis are needed because if we used |group_container, element, index| we would never know if we are destructing the first or the second parameter, so the parenthesis there works as disambiguation.

    9In fact, things works a bit different in the bottom end, but lets hide this for this given question.)

提交回复
热议问题