我如何逐行使用Ruby将csv转换为数组?

输入文件如下:

狗,白,男性
猫,紫,女
大鼠,灰色,男性

我希望逐行完成并对数据做一些事情。

File.open("animals.csv") while file has next line currentline = array with each cell being an entry in the array if currentline[0] == dog put "dogs are cool" end put "your animal is a " + currentline[0] end 

你明白了,对吗? 我想用ifs和whatnot操纵数据线,并在最后打印出来。

谢谢

Ruby包含一个CSV类,使得解析和使用CSV更加简单。 查看: http : //www.ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html

 require 'csv' CSV.foreach("animals.csv") do |row| puts 'dogs are cool' if row[0] == 'dog' puts "your animal is a #{row[0]}" end 

您可以使用块的魔力来清理行读取代码。 下面的代码将为您关闭您的句柄,并且每次只能获得一行,而无需额外的缓冲。

 IO.foreach("animals.csv") do |line| parts = line.split(',') ... end 

如上所述,有一个CSV库,但如果您的数据并不复杂,没有嵌入的逗号和whatenot,则上述内容是合理的。

另请注意,您要比较字符串“dog”而不是名为dog的变量。 要使字符串用引号括起来,否则ruby会将其视为变量或方法调用。

 if currentline[0] == "dog"