CSV中非常奇怪的行为(Ruby 2)

时间:2014-01-18 12:40:41

标签: ruby

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块无法执行。删除它一切都很好。发生了什么事?

1 个答案:

答案 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