If a csv file has multiple columns with same name, how to get all the values of these columns.
CodePudding user response:
# file.csv
name,name
one,two
Because you cannot use []
method to access all the duplicate columns, you can just break it up into an 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"]}]