I was practicing ruby inject method and found one strange output:
def adding(*num)
res = num.inject{|sum,n| sum + n}
puts "sum:::::::::::::::::::#{res.inspect}"
puts "sum:::::::::::::::::::#{res.class}"
end
adding ([1,2,3,4,5])
Output:
sum:::::::::::::::::::[1, 2, 3, 4, 5]
sum:::::::::::::::::::Array
While when we do:
[1,2,3,4,5].inject{|sum,n| sum + n}
Output:
15
Why this strange output? In method call, adding([1,2,3,4,5]), it should also return 15.
What is the reason for this strange output?
num is not what you think it is.
def adding(*num)
num # => [[1, 2, 3, 4, 5]]
end
adding([1,2,3,4,5])
Either don't do the splat
def adding(num)
or pass numbers separately
adding(1, 2, 3, 4, 5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With