Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why ruby inject method is not returning the sum inside a method

Tags:

ruby

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?

like image 721
2017kamb Avatar asked Sep 24 '26 05:09

2017kamb


1 Answers

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)
like image 143
Sergio Tulentsev Avatar answered Sep 26 '26 18:09

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!