Last Updated: February 25, 2016
· ashrocket

Beware Ruby Numeric functions inside Enumerable.inject

I recently had array read in from CSV, say ['500','1000','20'] for example.
I needed to sum these, and didn't want to convert it to a GSL::Vector to do the summation.
So I turned to the handy old ruby array.inject method like so:

a = ['500','1000','20'] 
Total = a.inject(:+)
=> "5001000020"

That's not what I expected. Mostly because I forgot to convert my file data to actual ints or floats.
Had I done this first:

a = ['500','1000','20'] 
a.map!{|v| v.to_f}
Total = a.inject(:+)
=>  1520.0

Now that's more like it :)

Inject is awesome, but if you are coding till 3 in the morning, you might just end up with a HUGE number in that Statistical function your are writing.


On a related note! Avoid the problem all together by having your file read properly in the first place:

                         {:headers => "event_time,some_number,name,duration,count,rate,tags,title",
                          :header_converters => :symbol,
                          :converters => :all})

And yes, that magic :all seems to be pretty smart about converting types into the right things, but make sure and check it before trusting it.