我在Ruby中实现,我只想读取CSV文件。我的CSV看起来像:
"official_code","username","lastname","firstname","email","Course Groups","password"
"1626","000078sr","LENS","Ser","blab@hogent.be","project1g43","pwd7975"
"7334","000116jd","DE ","Joen","je0116@.hogent.be","project1g08","pwd5259"
"2003","000136bv","VACKE","Bert","hogent.be","project1g18","pwd5908"
"4065","000166cr","ROHøJ","Chrian","chrhogent.be","project1g10","pwd5000"
它在Excel中制作并设置为CSV文件
但是当我在我的申请中时:
FasterCSV.foreach(file.path, {:headers=>true }) do |row|
@samples[i] = row
i += 1
end # do
if @samples.size > 0
@headers = @samples[0].headers
end
在我看来我只是这样做:
<%= @headers.inspect %>
<ul>
<% @samples.each do |a| %>
<li>
<%= a %>
</li>
<% end %>
</ul>
我明白了:
["\"official_code\",\"username\",\"lastname\",\"firstname\",\"email\",\"Course Groups\",\"password\""]
"""1626"",""000078sr"",""ENS"",""Sder"",""san.hogent.be"",""project1g43"",""pwd7975"""
"""7334"",""000116jd"",""DE VOS"",""Jen"",""jeroen.ogent.be"",""project1g08"",""pwd5259"""
"""2003"",""000136bv"",""VYCKE"",""Bet"",""berent.hogent.be"",""project1g18"",""pwd5908"""
"""4065"",""000166cr"",""ROøJ"",""Chstian"",""chr.hogent.be"",""project1g10"",""pwd5000"""
所以有很多方法。有人知道我做错了吗?就像行只有1列。如果我做samples[0].each
我只得到1项。整行和不是专栏。
答案 0 :(得分:0)
当您引用@samples
时,您正在查看行的数组,每个行都是已解析字段的数组。
因此,当您使用@samples.each do |a|
时,a
就是一行,我认为您正在获得在该行上调用#inspect
的结果。
如果你尝试这样的事情会怎样?
options = { :headers=>true, :return_headers => true }
@samples = FasterCSV.read(file.path, options).to_a
if @samples.size > 0
@headers = @samples.shift
end
如果您想获得实际标签,则需要:return_headers=>true
; :headers=>true
只告诉FasterCSV有标题 - 默认情况下会丢弃它们。 FasterCSV.read
获取并解析一次命中中的所有数据,这比自己构建数组更简单。注意最后的to_a
,这会强制结果真的是一个数组 - 它可能会使下一部分更简单。
如果您按如下方式修改视图会发生什么情况(在标题上使用#join
而不是#inspect
并在行上添加#join
?
<%= @headers.join(', ') %>
<ul>
<% @samples.each do |a| %>
<li>
<%= a.join(', ') %>
</li>
<% end %>
</ul>
如果这不能解决问题,希望你至少应该进一步了解正在发生的事情......