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

swa*_*way 3 ruby csv parsing

输入文件看起来像:

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

我想逐行检查并处理这些数据。

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
Run Code Online (Sandbox Code Playgroud)

你明白了,对吧?我想用 ifs 和诸如此类的东西来操作数据行,并在最后将其全部打印出来。

谢谢

Abe*_*ker 5

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


小智 2

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