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. , Then 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. to 3 (first array value).

  • Calculate our block as 0 + 3 as 3 and gives it.
  • # injection forces our block, prefix_sum to 3 (return value) and number < / Code> to 1 (second array value)
  • calculate our block as 3 + 1 as 4 and Returns it
  • # injection forces our block, binding prefix_sum 4 and number 4 (third array value)
  • Calculate our block as 4 + 4 as 8 and gives it.
  • # injection forces our block, binding prefix_sum 8 and number 1 (fourth array value)
  • Calculate our block as 8 + 1 as 9 and returns it .
  • # injection forces our block, binding prefix_sum 9 and number 5 (fifth array value)
  • Calculate our block as 9 + 5 as 14 and returns it.
  • # injection forces our block, binding prefix_sum 14 and number 9 (sixth array value)
  • Calculate our block as 14 + 9 as 23 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

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -