Reputation: 3208
String to float conversion using to_f
is not working for me.
I'm trying pick a column from the longitude and latitude data as below.
"136.98355","35.130433333333336","2013-07-31T22:37:12+09:00","2346","13066","42","0","0","0"
"136.98363333333333","35.1306","2013-07-31T22:38:13+09:00","1311","13580","41","0","0","0"
"136.98361666666668","35.130583333333334","2013-07-31T22:39:13+09:00","3946","13580","41","0","0","0"
When I simply grab the column using the below code, it works.
ruby -e "STDIN.readlines.each do |line| col = line.chomp.split(','); puts col[0] end" < new.csv > picked_nagoya.csv
Result:
"136.98355"
"136.98363333333333"
"136.98361666666668"
But when I apply to_f
to convert strings into floats, the file picked_nagoya.csv
is empty.
I tried to work it around by storing converted string into a variable and then writing it out to the file. However, it then returns 0.0s.
ruby -e "STDIN.readlines.each do |line| col = line.chomp.split(','); f = col[0].to_f; puts f end" < new.csv > picked_nagoya.csv
Result:
0.0
0.0
0.0
What am I doing wrong here?
Upvotes: 0
Views: 521
Reputation: 211570
Using the Ruby CSV parser you can extract the data and work with this:
require 'csv'
CSV.readlines('data.csv').each do |row|
lat, lng = row.first(2).map(&:to_f)
p [ lat, lng ]
end
Gives you output like:
[136.98355, 35.130433333333336]
[136.98363333333333, 35.1306]
[136.98361666666668, 35.130583333333334]
Upvotes: 1
Reputation: 20076
It's because to_f
is expecting a number, but the first character of the string you're trying to convert is actually a quotation mark: "123.456"
You'll need to trim the quotes off the string before you do any conversion:
f = col[0].delete_prefix('"').delete_suffix('"').to_f
Upvotes: 2