如果csv文件中有多个相同名称的列,如何获取这些列的所有值
# file.csv
name,name
one,two
由于不能使用[]
方法访问所有重复列,因此可以将其分解为Array
>> csv = CSV.table('file.csv')
# if you just need the values
>> csv.to_a.last
=> ["one", "two"]
# if you need to know the column name call to `to_a` on each row
>> csv.flat_map(&:to_a)
=> [[:name, "one"], [:name, "two"]]
# to aggregate duplicate column values (assuming you know the duplicate column name ahead of time)
>> csv.map{|row| row.inject({names: []}){|h,(column,value)| h[:names] << value if column == :name; h }}
=> [{:names=>["one", "two"]}]