Reputation: 1481
I am trying to make factorial calculation here.
When I run this code, it returns me number 5. I suppose this code loops only once, so only number 5(attr) is added to array. Am I right, and what should I do?
And I don't want solution, I want advice :)
def factorial attr
array = []
attr.downto(1) do |x|
array << x
array.reduce(:*)
end
end
p factorial(5)
Upvotes: 0
Views: 34
Reputation: 23939
Ruby returns the value of the last expression in the method as the value, and that's the .downto
block. Your code definitely loops, but it reduces "5" times, and discards the value! So you're getting this, essentially:
(502)⚡️ irb
2.2.0 :001 > 25.downto(1) { |x| }
=> 25
Try moving your reduce
statement outside of the block (below), so the downto
stuffs the values into the array, then you reduce it using the *
operation.
Upvotes: 1