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?
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?
You can do this:
@test.inject(:+)
@test.inject(0, :+)[].inject(:+). I guess the OP wants a generic solution, not for 4 elements.sum = 0
@test.each { |el| sum+=el }
Enumerable#inject is the idiomatic solution.