gpt4 book ai didi

ruby-on-rails - 有什么方法可以确定 csv 是否带有标题或不在 rails 中

转载 作者:数据小太阳 更新时间:2023-10-29 07:49:53 27 4
gpt4 key购买 nike

编写一个只接受带标题的 csv 文件的应用程序。所以试图检测 csv 文件是否有标题。有没有办法做到这一点。

最佳答案

我在我的 test.text 文件中放了一些示例数据:

name,age,location
Ram,12,UK
Jadu,11,USA

以及我编写的用于检查 header 是否存在的代码:-

#!/usr/bin/env ruby

require 'csv'

csv = CSV.open("#{__dir__}/test.txt", :col_sep => ",", :headers => true )
p csv.read.headers
# >> ["name", "age", "location"]

现在您必须检查此数组是否与您的headers 值匹配。如果它匹配,那么你可以告诉,是的标题被应用。这段代码是在与 @tadman 完全相同的基础上编写的。说:

here's no standard way of defining headers in a CSV file, but convention dictates that the first line, and only the first line, is headers. People are free to do whatever they want and, in the process, make your life as a developer absolutely miserable.

要了解这些选项的含义 :col_sep, :headers 查看 CSV::new 的文档.

关于ruby-on-rails - 有什么方法可以确定 csv 是否带有标题或不在 rails 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24645186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com