0

I'm trying to write code that will take an array and give back the SUM of the array. First, is this the correct way to place the numbers into an array? It seems like there may be a problem with that based on the error.

    def total(num)
       x = []
       x << num
       puts x.inject(0){|a,b|a+b}

    end

Looks like a have a few problems here. First, I get this error when I call the method with sum([3,2,41,2]):

`total': wrong number of arguments (5 for 1) (ArgumentError) from calculator.rb:11

I also recall getting a error: cant't covert fixnum into array

Justin Phillip
  • 279
  • 2
  • 3
  • 10

1 Answers1

1

Your inject block is correct. Your argument error arises because you defined the method to take a single argument, but in your example, you call it with four arguments. If you want to use a variable number of arguments, you can use the splat operator *, which does various things- in this case, it will gather all undefined arguments into an array:

def total(*nums)
  nums.inject(0) {|a,b| a + b }
end

total(3,2,41,2) #=> 48

You can further simplify this using a symbol with inject:

nums.inject(0, :+) #=> 48

This works by sending the method denoted by the symbol to the accumulator, using each member of the array as an argument (equivalent to defining the block as {|a, b| a.send(:+, b) }).

And actually in this case, you don't need to define an initial value. Inject has a third form that will simply use the first member of the array as the initial value and sum the others onto it:

nums.inject(:+)
Zach Kemp
  • 11,736
  • 1
  • 32
  • 46
  • Hi @ZachKemp, thanks for the answer....thats helpful. I posted the question wrong wrong though...what i need is the sum if were to call: total([3,2,41,2]). Note the difference in that it is already an array. thanks – Justin Phillip Feb 09 '13 at 01:44
  • In that case, could your problem be that you've defined a method called `total` and are calling a method called `sum`? Also, you don't need to push anything into a new array if you're supplying the array as an argument. Just take the `*` out of the method and you should be good to go. – Zach Kemp Feb 09 '13 at 07:04