ruby-on-rails – 在ruby中迭代CSV
发布时间:2020-12-17 01:31:07 所属栏目:百科 来源:网络整理
导读:我想在 ruby中打印出一个CSV文件,但我想将其格式化.有没有办法在层次结构意义上格式化数据?这是我需要经历的列表的一小部分: ,"11: Agriculture,Forestry,Fishing and Hunting","111: Crop Production","222220: Soybean Farming","111120: Oilseed (excep
我想在
ruby中打印出一个CSV文件,但我想将其格式化.有没有办法在层次结构意义上格式化数据?这是我需要经历的列表的一小部分:
,"11: Agriculture,Forestry,Fishing and Hunting","111: Crop Production","222220: Soybean Farming","111120: Oilseed (except Soybean) Farming","111130: Dry Pea and Bean Farming","111140: Wheat Farming","112: Animal Production","112111: Beef Cattle Ranching and Farming","112112: Cattle Feedlots","112120: Dairy Cattle and Milk Production","112130: Dual-Purpose Cattle Ranching and Farming" 我的代码是: require 'csv' col_data = [] CSV.foreach("primary_NAICS_code.txt") {|row| col_data << row} puts col_data 这只是打印出来的一切.它是一个数组中的数组吗?就像是: CSV.foreach do |row| row.each do |line| puts line end end 任何帮助都会指引我朝着正确的方向前进. 我想获取格式化为这样的信息: |_ <~~ row 1 column 1 | |__<~ row 1 column 2 | | |__<~row 2 column 2 | | | |__ | | | | |__ etc... | | | | | |__ 解决方法
由于您的数据已经缩进,您只需转换/格式化它.这样的事情应该有效:
col_data.each do |row| indentation,(text,*) = row.slice_before(String).to_a puts indentation.fill("|").join(" ") + "_ " + text end 输出: |_ 11: Agriculture,Fishing and Hunting | |_ 111: Crop Production | | |_ 222220: Soybean Farming | | |_ 111120: Oilseed (except Soybean) Farming | | |_ 111130: Dry Pea and Bean Farming | | |_ 111140: Wheat Farming | |_ 112: Animal Production | | |_ 112111: Beef Cattle Ranching and Farming | | |_ 112112: Cattle Feedlots | | |_ 112120: Dairy Cattle and Milk Production | | |_ 112130: Dual-Purpose Cattle Ranching and Farming (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |