Im trying to read a column of String values from my DB. Im trying to convert them to floats. I have written the following method to do that
def initialize (db_listings)
db_listings.each do |listing|
name = listing.name
index = listing.id
lat_string = listing.latitude
long_string = listing.longitude
puts "name = #{name}"
puts "index = #{index}"
puts "Converting #{lat_string} to float"
puts "Converting #{long_string} to float"
if(lat_string == nil || long_string == nil )
lat_float = Float(9999)
long_float = Float(9999)
else
lat_float = Float(lat_string)
long_float = Float(long_string)
end
puts "Now printing floats"
puts lat_float
puts long_float
end
end
But I get the following error:
Throwing an error:ArgumentError: invalid value for Float(): ""
This is because it encountered an empty entry for that column.
My question is : WHy did the if else statement in my method not catch it?
How do I adjust my method for empty/invalid values in the database?
Thanks
From the error message I presume
lat_stringandlong_stringare empty strings rather thannil. You could useblank?to catch both nil and empty strings: