require 'csv'
require 'open-uri'
url = 'http://www.census.gov/popest/data/national/totals/2005/files/NST_EST2005_ALLDATA.csv'
data = open(url)
data.read # This line causes nothing in the CSV block to process
CSV.parse(data) do |row|
area = row[4]
population = row[5]
puts "#{area} #{population}"
end
puts 'I am here!' # This prints no matter whether data.read is present
我正在使用Ruby 2,在上面的代码中,放入data.read会导致CSV.parse块无法执行。删除它一切都很好。发生了什么事?
答案 0 :(得分:1)
data.read
不会将data
更改为csv字符串。您应该将data.read
的结果传递给CSV.parse
。或者您可以直接将open(url)
传递给CSV.parse
。
require 'csv'
require 'open-uri'
url = 'http://www.census.gov/popest/data/national/totals/2005/files/NST_EST2005_ALLDATA.csv'
CSV.parse(open(url)) do |row|
area = row[4]
population = row[5]
puts "#{area} #{population}"
end
puts 'I am here!' # This prints no matter whether data.read is present