irb - So maybe I'm not getting the idea in Ruby but I have a question about Enumerables inject -
The | M, K | What kind of thing does it have to do with pre-order order?
So why did people put a number .inject ()?
Alternatively, there is an easy way to know how to use it, and what exactly is its significance? Looking at this question, I hope you all know that I am very happy for any programming language and Ruby was my first choice.
Try for example.
number = [3, 1, 4, 1, 5, 9] sum = numbers.inject (0) Do it. Prefix_sum, number | Prefix_sum + number end # injection takes an argument and a block should take two values, and a new value must be returned.
In the above example, the argument for # injection is 0 , and block is done. Subfix_sum, number | Prefix_sum + number ending . The value to pass the block to two | Named between markers: prefix_sum and number .
Each value of the enumerable # injection has been passed as a second value in the block. 5 , then finally 9 . So in this example, the block will be applied six times; Once for each status in the number .
The first value given to a block (named prefix_sum ) is usually accumulator . Its initial value, value is called the first block by # injection , which is set by the argument given to # injection (in this example, < Code> 0 ). The return of the block determines the value of the accumulator ( prefix_sum ) for the next bottle of value block.
-
/ Code>
0and gets our block. to3(first array value). - Calculate our block as
0 + 3as3and gives it. -
# injectionforces our block,prefix_sumto3(return value) andnumber < / Code> to1(second array value) - calculate our block as
3 + 1as4and Returns it -
# injectionforces our block, bindingprefix_sum4andnumber4(third array value) - Calculate our block as
4 + 4as8and gives it. -
# injectionforces our block, bindingprefix_sum8andnumber1(fourth array value) - Calculate our block as
8 + 1as9and returns it . -
# injectionforces our block, bindingprefix_sum9andnumber5(fifth array value) - Calculate our block as
9 + 5as14and returns it. -
# injectionforces our block, bindingprefix_sum14andnumber9(sixth array value) - Calculate our block as
14 + 9as23and brings it back . Since there are no other array elements,
# inject returns 23 , and we will call sum for that code Binding. You can see an injection as a bracket on a list of items, in this example, calculucating:
(((( (0 + 3) + 1) + 4) + 1) + 5 + 9) This allows you to take any kind of action, which is usually Moves on a pair, and applies it to a list.
Comments
Post a Comment