1

I have this array:

array = ["1", "Hel", "6", "3", "lo" ] .

I want to output sum of the integers only, which is 10. How do I do that?

3 Answers 3

6

just do :

array.inject(0) { |sum,n| sum + n.to_i } # => 10

#to_i will convert all the non integer strings to 0. But there is no problem, as for that over all summation will not be affected.

Sign up to request clarification or add additional context in comments.

1 Comment

Most process efficient so far. Benchmarked and this is faster than array.map(&:to_i).reduce(0, :+) (1.49s vs. 2.05s for 1000000 times for me)
5

String#to_i will return 0 in your example so we can use it to map over all array elements.

array.map(&:to_i).reduce(0, :+)

3 Comments

Don't need to set initial for this problem, e.g. this produces same result: array.map(&:to_i).reduce(:+). This is because initial defaults to the first item in the array, and even if to_i were to be called on a string or nil, both evaluate to 0, in Ruby 2.1 at least.
@GaryS.Weaver it's there to provide a robust solution: [].reduce(:+) # nil and [].reduce(0, :+) # 0
Good catch! You're right, that was probably the intent.
0

Since Ruby 2.4 array has an Enumerable#sum method.

array.sum(&:to_i)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.