+ 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.
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 :) )
+ 1
the output is not 20 but [6,14]
edited : I switched 6 and 4 ^^'
+ 1
Yes @Lord Kirshna, I switched 6 and 4 by mistake, sorry ^^
+ 1
To. Baptiste E. Prunier
Your code works well.
The explanation using for loop is easy to understand.
Thanks.
+ 1
@Aris Kim my pleasure :)