来自 csv 的具有相同名称的多个列的值

Values from mltiple columns with same name from csv

如果一个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"]}]