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?

1

2 Answers 2

4

You can do this:

@test.inject(:+)
Sign up to request clarification or add additional context in comments.

5 Comments

folds need the identity as initial value : @test.inject(0, :+)
Not with ruby, if you don't supply an initial value, it uses the first value in the collection as the initial value: ruby-doc.org/core-1.9.3/Enumerable.html
@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 )
jesse, steenslag: not for empty inputs: [].inject(:+). I guess the OP wants a generic solution, not for 4 elements.
0
sum = 0
@test.each { |el| sum+=el }

1 Comment

that's ok for a lot of (imperative) languages, but in Ruby the (functional) Enumerable#inject is the idiomatic solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.