Last Updated: February 25, 2016
·
1.043K
· 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.

http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-inject
http://ruby-doc.org/core-2.0.0/String.html#method-i-2B

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

CSV.read("data/my.csv",
                         {: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.

http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-i-converters