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?
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.
array.map(&:to_i).reduce(0, :+) (1.49s vs. 2.05s for 1000000 times for me)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, :+)
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.[].reduce(:+) # nil and [].reduce(0, :+) # 0