+ 1

Ruby syntax : Who can explain this code easily?

The inject method is so compact and efficient but very difficult. Can someone explain this code in a plain language or step by step? The code : a = (1..3).inject([0,0]){|sum,i| [sum[0]+i, sum[1]+i**2]} print a # Output : Yes you're right Baptiste, the output is [6, 14]. and Can you explain how the result is derived? You're excellent!!! I just understood your explanation. And the code works well.

12th Aug 2017, 4:37 PM
Aris Kim
Aris Kim - avatar
5 ответов
+ 2
it does this (in detail) sum=[0,0] for i in (1..3) do sum[0]+=i sum[1]+=i**2 end (there might be syntax error, I am not really good in ruby :) )
12th Aug 2017, 4:12 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
the output is not 20 but [6,14] edited : I switched 6 and 4 ^^'
12th Aug 2017, 4:09 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
Yes @Lord Kirshna, I switched 6 and 4 by mistake, sorry ^^
12th Aug 2017, 4:13 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
To. Baptiste E. Prunier Your code works well. The explanation using for loop is easy to understand. Thanks.
12th Aug 2017, 4:30 PM
Aris Kim
Aris Kim - avatar
+ 1
@Aris Kim my pleasure :)
12th Aug 2017, 4:45 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar