1

Possible Duplicate:
How to sum array members in Ruby?

Lets say I have this array

@test = [1, 2, 3, 4]

Then I want to do:

@test[0] + @test[1] + @test[2] + @test[3]

Is there not a smarter, faster way of doing this?

Community
  • 1
  • 1
Rails beginner
  • 14,321
  • 35
  • 137
  • 257

2 Answers2

4

You can do this:

@test.inject(:+)
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
  • folds need the identity as initial value : `@test.inject(0, :+)` – tokland Jan 15 '12 at 21:46
  • 1
    Not with ruby, if you don't supply an initial value, it uses the first value in the collection as the initial value: http://ruby-doc.org/core-1.9.3/Enumerable.html – Jesse Pollak Jan 15 '12 at 21:50
  • @tokland: "If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo." (from [the docs](http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-inject) ) – steenslag Jan 15 '12 at 21:53
  • More directly: http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-inject – Dave Newton Jan 15 '12 at 21:53
  • jesse, steenslag: not for empty inputs: `[].inject(:+)`. I guess the OP wants a generic solution, not for 4 elements. – tokland Jan 15 '12 at 21:57
0
sum = 0
@test.each { |el| sum+=el }
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
falinsky
  • 7,229
  • 3
  • 32
  • 56
  • that's ok for a lot of (imperative) languages, but in Ruby the (functional) `Enumerable#inject` is the idiomatic solution. – tokland Jan 15 '12 at 22:03