如何使用Ruby逐行将csv转换为数组? [英] How do I, line by line, turn a csv into an array using Ruby?
本文介绍了如何使用Ruby逐行将csv转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
输入文件如下:
dog,white,male
cat,purple,female
rat,gray,male
我想逐行处理该数据.
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操纵数据行,并在最后全部打印出来.
You get the idea, right? I want to manipulate data line with ifs and whatnot and print it all out at the end.
谢谢
推荐答案
require 'csv'
CSV.foreach("animals.csv") do |row|
puts 'dogs are cool' if row[0] == 'dog'
puts "your animal is a #{row[0]}"
end
这篇关于如何使用Ruby逐行将csv转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文