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>
0
and gets our block. to3
(first array value). - Calculate our block as
0 + 3
as3
and gives it. -
# injection
forces our block,prefix_sum
to3
(return value) andnumber < / Code> to
1
(second array value) - calculate our block as
3 + 1
as4
and Returns it -
# injection
forces our block, bindingprefix_sum
4
andnumber
4
(third array value) - Calculate our block as
4 + 4
as8
and gives it. -
# injection
forces our block, bindingprefix_sum
8
andnumber
1
(fourth array value) - Calculate our block as
8 + 1
as9
and returns it . -
# injection
forces our block, bindingprefix_sum
9
andnumber
5
(fifth array value) - Calculate our block as
9 + 5
as14
and returns it. -
# injection
forces our block, bindingprefix_sum
14
andnumber
9
(sixth array value) - Calculate our block as
14 + 9
as23
and 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